Dimas Putra
Dimas Putra

Reputation: 139

PHP XML: How To Get The NodeValue by Its Siblings?

Example of the xml:

<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>

I want to make a function that return the released date of a book title. Ex: I want to get released date of the 'Hip Hop Hippo' book.

I know I can use simplexml and write ->book[0]->released. But that's only works when I have a static XML and I know where the ->book[$i]->title that match 'Hip Hop Hippo'. But not in dynamic case. I can't predict every changes, since it came from an API provider. It can be book[1], book[2], and so on.

What should I write in my function?

Upvotes: 0

Views: 743

Answers (1)

Scuzzy
Scuzzy

Reputation: 12322

Check out the xpath functions http://php.net/manual/en/simplexmlelement.xpath.php

You will then be able to write a query like: /books/book[title="Hip Hop Hippo"]

$string = <<<XML
<books>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-9999</released>
  </book>
  <book>
    <title>Hip Hop Hippo</title>
    <released>31-12-2000</released>
  </book>
  <book>
    <title>Bee In A Jar</title>
    <released>01-01-0001</released>
  </book>
</books>
XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/books/book[title="Hip Hop Hippo"]');

foreach($result as $key=>$node)
{
  echo '<li>';
  echo $node->title . ' / ' . $node->released;
  echo '</li>';
}

Upvotes: 3

Related Questions