Select xml node by attribute in php

2019-01-28 23:32发布

问题:

How do I find the node value by knowing the attribute value without traversing through every child and every attribute/value ?

$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>

回答1:

The simplest thing to do is use DOMXPath::querydocs

The following code finds all the <field> nodes within <row> nodes that have a name attribute equal to "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;
}

Using the sample xml you provide, the above outputs:

blah blah 1
blah blah 2