2

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
  • You can't... Even if you use a library, in the back end, it's going to have to traverse the tree to find what you're looking for. Commented Feb 12, 2012 at 21:52

1 Answer 1

5

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 
Sign up to request clarification or add additional context in comments.

2 Comments

I had thought about xpath as well but it will only allow me to select one field? I need several variables populated for each "row"
I'm not sure if this is what you're asking but you can just stack up the attribute conditions like so: $query = "//row/field[@name='header'][@other_attr='anything']"; If you're asking if you can grab multiple types of elements with a single xpath, then no. You could do multiple xpath queries or loop over all of them. Sorry if that's what you were asking in the first place. "find the node value by knowing the attribute value" -- which is what your question says -- is an xpath situation, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.