naveencgr8
naveencgr8

Reputation: 341

Grab and Store Data from XML

I'm trying to get data from a API that output data in XML structure.

It has a lot branches, looks complicated. Here is the structure,

<rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<channel>
<item>
<title>Test Video</title>
<media:content url="http://localhost/video/test.mp4" type="video/x-flv" duration="6474"/>
</item>
</channel>
</rss>

I would also like to know what if it got more branches such as video description, type.. how can I grab them? and inside media tag it has multiple values, how can I get them separately? example: how to get the content url inside media tag?

Upvotes: 1

Views: 419

Answers (3)

Bass Jobsen
Bass Jobsen

Reputation: 49044

Yes you can use SimpleXMl. <media:content> refers to a namespace (http://search.yahoo.com/mrss/). So you can use:

$string = <<<XML
<rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<channel>
<item>
<title>Test Video</title>
<media:content url="http://localhost/video/test.mp4" type="video/x-flv" duration="6474"/>
</item>
</channel>
</rss>
XML;

$xml = simplexml_load_string($string);

//var_dump($xml);
echo $xml->channel->item->title;
$contentAttr = $xml->channel->item->children('media', true)->content->attributes();
echo $contentAttr['url'];

exit;

Take also a look at Using SimpleXML to read RSS feed

Upvotes: 1

michi
michi

Reputation: 6625

I realize there's a namespace in your XML (line 1), this will do the trick:

$xml = simplexml_load_string($x); // assuming your XML in $x
$contents = $xml->xpath("//media:content");

foreach ($contents as $content) echo $content['url'],"<br />";

See live demo: http://codepad.viper-7.com/7bJf9Q

Alternatives: look for namespace and simplexml.

Upvotes: 2

michi
michi

Reputation: 6625

Take a look at simplexmlor DOMDocument at php.net.
These provide functions to parse XML-data.
The url inside the <media:content> is called an attribute, the above functions provide ways to pull the attributes, as well.

I suggest you try something with the info I've given, and return to SO in case you need help, ok?

Have fun trying!

Upvotes: 0

Related Questions