使用 SimpleXml 在 PHP 中访问具有不同节点名称的 XML 的第 n 个元素
Accessing nth element of XML with different node names in PHP with SimpleXml
当 XML 节点的所有 children 具有相同的名称时,在 PHP 中使用 SimpleXml 您可以使用 $xml-> 轻松访问第 n 个元素foo[$nth]。
( Accessing nth element of XML in PHP with SimpleXml )
如果 children 有不同的名称,如何获取第 n 个元素?
例如在这样的 xml 中:
<?xml version="1.0"?>
<root>
<foo id="11" />
<foo id="2" />
<bar id="10" />
<foo id="8" />
</root>
我想知道第三个元素是 'foo' 还是 'bar' 而无需遍历所有节点。
提前致谢!
您可以使用 children()
方法:
$xml = simplexml_load_file('file.xml');
$childrens = $xml->children();
var_dump($childrens[1]); // <foo id="2" />
var_dump($childrens[2]); // <bar id="10" />
Link: http://php.net/manual/en/simplexmlelement.children.php
当 XML 节点的所有 children 具有相同的名称时,在 PHP 中使用 SimpleXml 您可以使用 $xml-> 轻松访问第 n 个元素foo[$nth]。 ( Accessing nth element of XML in PHP with SimpleXml ) 如果 children 有不同的名称,如何获取第 n 个元素?
例如在这样的 xml 中:
<?xml version="1.0"?>
<root>
<foo id="11" />
<foo id="2" />
<bar id="10" />
<foo id="8" />
</root>
我想知道第三个元素是 'foo' 还是 'bar' 而无需遍历所有节点。
提前致谢!
您可以使用 children()
方法:
$xml = simplexml_load_file('file.xml');
$childrens = $xml->children();
var_dump($childrens[1]); // <foo id="2" />
var_dump($childrens[2]); // <bar id="10" />
Link: http://php.net/manual/en/simplexmlelement.children.php