views:

670

answers:

4

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.

+1  A: 

Try $sxml->entry[4]->thumb or something to that regard.

AKA, to access the first entries ID, you would go $sxml->entry[4]->id

Basically $sxml->entry is an array of SimpleXMLElement Objects. When you foreach them, you are going through each object and assigning it to $entry, so that $entry = $sxml->entry[0] and upwards.

You can go like this:

print_r($sxml);

to see the ENTIRE structure. And that will tell you what you need to use to access it.

Chacha102
I edited my question to clarify one thing. I'm actually making the calls in the HTML outside of the PHP using inline echoes. I've just got the print_r in the PHP block for testing. Apologies on not clarifying that earlier. Thanks so, so much for your help thus far.
Joshua Cody
See if `$sxml->entry[4]->id` will work.
Chacha102
Great, thanks so much for the clarification on just what's happening here. If you hadn't noticed, I'm a bit above my pay grade here, but I'm **very** interested in learning the why instead of the how. That's good to know the foreach is traversing the separate objects.
Joshua Cody
I'm a 16 year old with nothing to do. I'm way **below** my pay grade :)
Chacha102
Joshua Cody
I'm not completely sure what the problem is. Just play around with it and I'm sure you'll be able to find it.
Chacha102
+3  A: 

You ran into the problem of namespaces and SimpleXML. The feed starts with

<feed xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'&gt;

The xmlns='http://www.w3.org/2005/Atom' sets the default namespace to http://www.w3.org/2005/Atom. I.e. its child elements are not really id, updated, category but http://www.w3.org/2005/Atom:id, http://www.w3.org/2005/Atom:updated and so on...
So you can't access the the id element via $feed->id, you need the method SimpleXMLELement::children(). It let's you specify the namespace of the child elements you want to retrieve. E.g.

$feed = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos?author=ofcoursegolf&amp;max-results=5&amp;prettyprint=true');
$children = $feed->children('http://www.w3.org/2005/Atom');
echo $children->updated;

(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 the xmlns:media='http://search.yahoo.com/mrss/' namespace.

$feed = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos?author=ofcoursegolf&amp;max-results=5&amp;prettyprint=true');
$group = $feed->children('http://www.w3.org/2005/Atom')
  ->entry[0]
  ->children('http://search.yahoo.com/mrss/')
  ->group
  ->children('http://search.yahoo.com/mrss/')
;
echo $group->player->attributes()->url, "\n";
foreach( $group->thumbnail as $thumb) {
  echo 'thumb: ', $thumb->attributes()->url, "\n";
}

(currently) prints

http://www.youtube.com/watch?v=ikACkCpJ-js&amp;feature=youtube_gdata
thumb: http://i.ytimg.com/vi/ikACkCpJ-js/2.jpg
thumb: http://i.ytimg.com/vi/ikACkCpJ-js/1.jpg
thumb: http://i.ytimg.com/vi/ikACkCpJ-js/3.jpg
thumb: http://i.ytimg.com/vi/ikACkCpJ-js/0.jpg

edit: I'd probably do that within the browser with a lot more javascript but here's a (simple, ugly) example app

<?php
//define('TESTENV' , true);
function getFeed($author) {
  // <-- add caching here if needed -->
  if ( !defined('TESTENV') ) {
    $url = sprintf('http://gdata.youtube.com/feeds/api/videos?author=%s&amp;max-results=5',
      urlencode($author)
    );
  }
  else {
    $url = 'feed.xml';
  }
  return simplexml_load_file($url);
}
$feed = getFeed('jonlajoie');

if ( !isset($_GET['id']) ) {
  $selected = '';
}
else {
  $selected =  $_GET['id'];
  printf ('
    <object width="425" height="344">
      <param name="movie" value="http://www.youtube.com/v/%s"&gt;&lt;/param&gt;
      <param name="allowFullScreen" value="true"></param>
      <param name="allowscriptaccess" value="always">
      </param>
      <embed src="http://www.youtube.com/v/%s" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>
    </object>',
    htmlspcialchars($selected), htmlspcialchars($selected)
  );
}

$item = 0;
foreach( $feed->children('http://www.w3.org/2005/Atom')-&gt;entry as $entry ) {
  $entryElements = $entry->children('http://www.w3.org/2005/Atom');
  $groupElements = $entry
    ->children('http://search.yahoo.com/mrss/')
    ->group
    ->children('http://search.yahoo.com/mrss/')
  ;

  if ( !preg_match('!^http://gdata.youtube.com/feeds/api/videos/([^/]+)!', $entryElements->id, $m) ) {
    // google can choose whatever id they want. But this is only a simple example....
    die('unexpected id: '.htmlspecialchars($entryElements->id));
  }
  $id = $m[1];
  if ( $selected!==$id ) {
    printf('<a href="?id=%s"><img src="%s" /></a>',
      urlencode($id),
      $groupElements->thumbnail[0]->attributes()->url
    );
  }
}

edit2: "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.

VolkerK
This is the best explanation of "namespace" I've seen. In my PHP, I'm currently accessing data in this way—specifying children('namespace'), but you've put great words to the tutorial I'm following. One thing I'm not understanding is how to call specific examples within my HTML. Should I simply generate all my HTML from within the PHP? I'm looking to load the most recent video in the main space by default, then the four thumbnails of the 2nd-5th videos. 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?
Joshua Cody
I feel like I'm getting somewhere tinkering with this. I want to see if I have it right. It says, for the variable "group," look for the children of namespace w3.org who are the first entry in an array. Then, look for children of the namespace yahoo for the node of "group." Then get the children of group in the yahoo namespace?
Joshua Cody
Joshua Cody
Whew, your edits are exhaustive. I'm going to sleep on this. I'm hesitant to throw away the PHP work I've done so far and start from scratch. But then again, your PHP solution above is honestly lost on me. I really need to get this to the client tomorrow. Frustrated at my lack of understanding as to why I can't wrap my head around this YouTube API and the XML return. I'm going to sleep on this, but I'll be back around tomorrow to mark this answer as correct as well as any other that can help me get my head around this stuff. Thanks so much for your help; it's been invaluable so far.
Joshua Cody
+2  A: 
$doc = new DOMDocument();
$doc->loadXML(file_get_contents('http://gdata.youtube.com/feeds/api/videos?author=ofcoursegolf&amp;max-results=5&amp;prettyprint=true'));
$xpd = new DOMXPath($doc);
$xpd->registerNamespace('atom', "http://www.w3.org/2005/Atom");
false&&$node = new DOMElement();//this is for my IDE to have intellysense

$result = $xpd->query('//atom:feed/atom:entry[1]/media:group/media:thumbnail');
foreach($result as $node){
    echo $node->getAttribute('url').'<br />';
}

echo "more results <br />";
$result = $xpd->query('//atom:feed/atom:entry[1]/media:group/media:thumbnail[1]');
foreach($result as $node){
    echo $node->getAttribute('url').'<br />';
}
A: 

In the end, I did two foreach loops, one running through an XML feed showing the most recent one entry. Then, I echoed out the object around this to play the vide.

In the other, I ran through the most recent four entries, returning list elements for a list of thumbnails.

Now, when I click on a thumbnail video, javascript handles passing the parameters to the main entry. Now, how to reload that main object upon receiving the parameters, I'm open to ideas.

Joshua Cody