tags:

views:

119

answers:

2

My client's system needs to access private photos from their Flickr account using the flickr.photos.search API call. I set it up and got the generated URL for that call. When I visit that URL in the browser, it outputs XML like it should.

(API reference: http://www.flickr.com/services/api/flickr.photos.search.html)

However, in PHP I want to access that XML and display it using the simplexml PHP extension. I can't figure out how to access the XML, since it's not sitting in a .xml file but rather in a dynamic URL.

The XML file (from the browser) looks like this:

<rsp stat="ok">
  <photos page="1" pages="1" perpage="100" total="4">
    <photo id="4332852622" owner="36520372@N05" secret="xxxxxxxx" server="2760" farm="3" title="building" ispublic="0" isfriend="0" isfamily="0"/>
    <photo id="4332113745" owner="36520372@N05" secret="xxxxxxx" server="2803" farm="3" title="digging" ispublic="0" isfriend="0" isfamily="0"/>
    <photo id="4332852444" owner="36520372@N05" secret="xxxxxxx" server="4025" farm="5" title="house" ispublic="0" isfriend="0" isfamily="0"/>
    <photo id="4332113699" owner="36520372@N05" secret="xxxxxxx" server="2802" farm="3" title="PaulLuomaHab" ispublic="0" isfriend="0" isfamily="0"/>
  </photos>
</rsp>

And with PHP I'm trying this:

$rsp = simplexml_load_file($flickrURL);
foreach($rsp->photos->photo as $photo) {
    echo $photo->title;
}

It returns nothing at all. Am I missing something here?

NOTE: I added echo "Ding!"; inside of the foreach loop above, and it DOES echo Ding!Ding!Ding!Ding!, which means it's recognizing there are 4 photos and looping through the right number of times.

So apparently it's just not happy with $photo->title for some reason?

Also

When I use print_r($photo) I get this:

SimpleXMLElement Object ( [@attributes] => Array ( [id] => 4332852622 [owner] => 36520372@N05 [secret] => 88fff62f43 [server] => 2760 [farm] => 3 [title] => building [ispublic] => 0 [isfriend] => 0 [isfamily] => 0 ) )
A: 

When using SimpleXML, you should always name your PHP variable after the node it represents. It helps keeping a clear idea of where you are in your XML tree. For instance, your code should be:

$rsp = simplexml_load_file($flickrURL);
foreach($rsp->photos->photo as $photo)
{
    echo $photo->title;
}
Josh Davis
Thanks, this is just a quick test to get it working. Unfortunately, renaming to $rsp and changing it to $rsp->photos->photo didn't work, either.
Jason Rhodes
A: 

I solved it on my own, doh. Title is an attribute of the XML element, and not a node, so it's accessed like an array rather than like an object attribute (confusing terminology).

So it's echo $photo['title']; and poof! it works.

Jason Rhodes