如何在不遍历每个子项和每个属性/值的情况下通过了解属性值来查找节点值?
$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>
最简单的方法是使用
原文链接:https://www.f2er.com/php/139026.htmlDOMXPath::query
docs
以下代码查找所有< field> < row>内的节点name属性等于“header”的节点:
$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