0

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?

0

1 Answer 1

3

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

3 Comments

Thanks! I've heard that function. But in the php manual, it doesn't explain what operators I can use in the bracket, like @, ., etc. Can you explain or link the explanation?
@ is for attributes values, the "." denotes current context and "../" can be used to recurse back up the xml tree eg //title[../released=""], double fowrad slash will start anywhere within the XML tree where single starting slash is from root
How about * and ::? Oh, and I see a comment in the php manual use conditional function like [. > '40']. So much xpath query that I don't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.