Helen
Helen

Reputation: 76

Simplexml: Select element by id a echo a certain child element

I'd need some advise with simplexml xpath. I have a master XML-file for my entire website like this:

<content>
<item id="001">
    <title>Video 1</title>
    <video>
        <file>video001.mp4</file>
        <dur>01:20</dur>
    </video>
</item>
<item id="2">
    <title>Video 2</title>
    <video>
        <file>video002.mp4</file>
        **<dur>03:53</dur>**
    </video>
</item>
</content>

Now I want to echo the duration of the video of item with the id "2" which would be the string "03:53".

Seems to be the simples use of simplexml, but the tons of tutorials out there only cover loops and selection by array number. I want to access a parent element by its id an grab the string of a certain child element of it.

Thanks in advance! Runa

Upvotes: 1

Views: 708

Answers (1)

jmarceli
jmarceli

Reputation: 20192

You may use XPath for that purpose: http://php.net/manual/en/simplexmlelement.xpath.php

You code should look like this (more or less):

$xml = simplexml_load_file('path/to/xml/file.xml');
$result = $xml->xpath('/content/item[@id=2]/video/dur/text()');
$result = $result[0];
echo $result;

Here is phpFiddle http://phpfiddle.org/main/code/9hc-yqi

Probably you should also cast xpath result on string but I'm not sure. I just tested xpath part of this code inside http://www.xpathtester.com/ and it works just fine.

Upvotes: 1

Related Questions