David Doria
David Doria

Reputation: 10273

Get an xml object by attribute

I can display all of the elements in an xml using this:

foreach($xml->children() as $child)
  {
  echo $child->title;
  }
?>

but how would I, say, display the 'author' of the book who's title is 'The Cat in the Hat'? That is, how do I get an object of a child with a specific attribute?

Thanks,

David

Upvotes: 0

Views: 230

Answers (3)

David Doria
David Doria

Reputation: 10273

Ah, this seems to do the job:

$res = $xml->xpath("/bookstore/book[title = 'Everyday Italian']"); 

echo $res[0]->author

?>

There are some nice explanations here: http://www.w3schools.com/XPath/xpath_syntax.asp

Thanks for the pointer!

David

Upvotes: 1

David Doria
David Doria

Reputation: 10273

The structure is like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book>
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>

The only terminology I know is that "bookstore" is the "root node". What is the difference between a 'parent node' and a 'child node' in your reply?

If I am looking to output the author of the book named "Everyday Italian", would it look something like this:

<?php
$xml = simplexml_load_file("bookstore.xml");

$arrayOfNodes = $xml->xpath('//parent[@title="Everyday Italian"]/*');

foreach ($arrayOfNodes as $node) {
   echo $node->author;
}

?>

?

Thanks, David

Upvotes: 0

netcoder
netcoder

Reputation: 67695

This can easily be done with XPath. Not sure what you want exactly though.

$sxml = new SimpleXMLElement($xml_string);
$arrayOfNodes = $sxml->xpath('//child[@attr="value"]/..');
foreach ($arrayOfNodes as $node) {
   // do stuff
}

The above will get you all the nodes that contain a <child> node with a attr="value" attribute.

$sxml = new SimpleXMLElement($xml_string);
$arrayOfNodes = $sxml->xpath('//parent[@attr="value"]/*');
foreach ($arrayOfNodes as $node) {
   // do stuff
}

The above will get you all the children of a <parent> node with a attr="value" attribute.

Of course, if you provided the XML structure, I could make this example less generic.

Upvotes: 1

Related Questions