Nickl
Nickl

Reputation: 1473

Php & XML - Get item by id

I've got an XML file like this:

<item id="55">
<title>Title</title>
...
</item>

and a php file which puts the XML data on an array...

foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        );
    array_push($feed, $item);
}

But how can I only get only one item on based on the id attribute?

I tried this but didn't work...

foreach ($rss->getElementsById('55') as $node) {

Upvotes: 1

Views: 2334

Answers (1)

michi
michi

Reputation: 6625

use xpath to select nodes with specific attributes only. In my example, I use simplexml:

$xml = simplexml_load_string($x); // assume XML in $x
$node = $xml->xpath("//item[@id='55']")[0];

echo $node->title;

Upvotes: 2

Related Questions