Sunday, January 5, 2014

php simplexml get a specific item based on the value of a field

Is there a way i can obtain a specific item with SimpleXML ?

For example, i would like to obtain the title of an item having ID set to 12437 with this example xml :

<items>  <item>    <title>blah blah 43534</title>    <id>43534</id>  </item>  <item>    <title>blah blah 12437</title>    <id>12437</id>  </item>  <item>    <title>blah blah 7868</title>    <id>7868</id>  </item></items>

Here are 2 simple ways of doing what you want, one is iterating with each item like this:

<?php$str = <<<XML<items><item><title>blah blah 43534</title><id>43534</id></item><item><title>blah blah 12437</title><id>12437</id></item><item><title>blah blah 7868</title><id>7868</id></item></items>XML;$data = new SimpleXMLElement($str);foreach ($data->item as $item){    if ($item->id == 12437)    {        echo "ID: " . $item->id . "\n";        echo "Title: " . $item->title . "\n";    }}

Live DEMO.

The other would be using an XPath, to pin point the exact data you want like this:

<?php$str = <<<XML<items><item><title>blah blah 43534</title><id>43534</id></item><item><title>blah blah 12437</title><id>12437</id></item><item><title>blah blah 7868</title><id>7868</id></item></items>XML;$data = new SimpleXMLElement($str);// Here we find the element id = 12437 & obtain it's parent$nodes = $data->xpath('//items/item/id[.="12437"]/parent::*');$result = $nodes[0];echo "ID: " . $result->id . "\n";echo "Title: " . $result->title . "\n";

Live DEMO.

No comments:

Post a Comment