如何通过了解属性值而不遍历每个子节点和每个属性/值来找到节点值?
$dom = new DOMDocument;
$dom->load('test.xml');
$rows = $dom->getElementsByTagName('row');
foreach ($rows as $row) {
$header = VALUE OF <field name="header">
$text = VALUE OF <field name="text">
}
XML:
<resultset>
<row>
<field name="item">2424</field>
<field name="header">blah blah 1</field>
<field name="text" xsi:nil="true" />
...
</row>
<row>
<field name="item">5321</field>
<field name="header">blah blah 2</field>
<field name="text">some text</field>
...
</row>
</resultset>
答案 0 :(得分:5)
最简单的方法是使用DOMXPath::query
docs
以下代码查找<field>
个节点中名称属性等于“header”的所有<row>
个节点:
$dom = new DOMDocument;
$dom->loadXML($str); // where $str is a string containing your sample xml
$xpath = new DOMXPath($dom);
$query = "//row/field[@name='header']";
$elements = $xpath->query($query);
foreach ($elements as $field) {
echo $field->nodeValue, PHP_EOL;
}
使用您提供的样本xml,上面的输出:
blah blah 1
blah blah 2