I’m using simpleXML to parse this xml file. It’s a feed I’m using to access the YouTube API. I want to embed the most recent video in an object and display the next four thumbnails.
So I’m using simplexml_load_file on this, going using a foreach loop to access the values in each feed.
I can access the values no problem, but I run into the problem that it stores each video in a separate SimpleXMLElement Object. I don’t have any control over which object I’m accessing as they are not stored in an array. So I can’t get, say, $thumb[4] or $entry[4]->thumb.
I tried to use SimpleXMLIterator, but for whatever reason, any values that have the same beginning render as blank. For example, the video could have eleven variations of:
And these would each render as [1]="", [2]="", [3]="", etc.
I’ll happily provide some more information to anyone who can help!
Edit
Here is the print_r of my results. This is done on a single variable to give you an idea of the structure issue I’m facing. The entire print_r($entry) would give variables for each node in the XML file.
SimpleXMLElement Object
(
[0] => 159
)
SimpleXMLElement Object
(
[0] => 44
)
Also, the print_r is simply inside the PHP block for testing. I’m actually looking to access the variables within echoes in the HTML.
You ran into the problem of namespaces and SimpleXML. The feed starts with
The
xmlns='http://www.w3.org/2005/Atom'sets the default namespace tohttp://www.w3.org/2005/Atom. I.e. its child elements are not reallyid,updated,categorybuthttp://www.w3.org/2005/Atom:id,http://www.w3.org/2005/Atom:updatedand so on…So you can’t access the the id element via
$feed->id, you need the method SimpleXMLELement::children(). It lets you specify the namespace of the child elements you want to retrieve.For example,
Currently prints
2010-02-06T05:23:33.858Z.To get the id of the first entry element you can use
echo $children->entry[0]->id;.But then you’ll hit the
<media:group>element and its children<media:category,<media:player>and so on…, which are in thexmlns:media='http://search.yahoo.com/mrss/'namespace.(Currently) prints
Edit: I’d probably do that within the browser with a lot more JavaScript, but here’s a (simple, ugly) example app.
Edit 2: “And when I click the thumbnails, I’ll use jQuery to load the video in the main space. Seems like I’ll need precise access to node[#], right?”
If you’re already using JavaScript/jQuery your PHP script (if needed at all) could simply return a (JSON encoded) array of all the data for all the video and your jQuery script could figure out what to do with the data.