1

Im trying to parse the following XML :

  <item><title><![CDATA[Van Gaal: Keep the faith]]></title><description><![CDATA[Manchester United manager Louis van Gaal is in a bullish mood ahead of Monday's trip to face West Brom in front of the Sky Sports cameras.]]>
   </description><link>http://www1.skysports.com/football/news/11667/9520895/premier-league-manchester-united-boss-louis-van-gaal-remains-confident</link>
   <guid isPermaLink="false">11661_9520895</guid>
   <pubDate>Fri, 17 Oct 2014 16:48:00 GMT</pubDate>
   <category>News Story</category>
   <enclosure type="image/jpg" url="http://img.skysports.com/14/09/128x67/football-louis-van-gaal-manchester-united_3202836.jpg" length="123456" /></item>

I am using the following code in my PHP script

$url = $xml->channel->attributes ()->items[$i]->enclosure->url;

But im not having much luck getting the url for the image. I have tried using the attribute() function, that didn't work.

Any suggestions would be gratefully appreciated .

Thanks

Kevin
  • 41,694
  • 12
  • 53
  • 70
n4zg
  • 387
  • 2
  • 6
  • 20

2 Answers2

1

I suggest use a foreach in this case. And you're almost at it.

foreach($xml->channel->item as $item) {
    $url = (string) $item->enclosure->attributes()->url;
    echo $url;
}
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Thank you. that worked great. would you be kind enough to look at the following for me I tried the solution you provided but it doesn't work with this one `` – n4zg Oct 18 '14 at 19:07
  • Of course it's doesn't work, it's not the same node. His answer is for enclosure node. If you want retrieve all URL attribute no matter the node, check my answer and use the xpath "//@url" – amdev Oct 18 '14 at 21:30
  • @n4zg you can use `->children()` function in that case – Kevin Oct 19 '14 at 04:09
0

You can use xpath "//enclosure/@url", it retrieve all URL

If you want just the first url "//enclosure[1]/@url"

if you're using simpleXML

$result = $xml->xpath("//enclosure/@url");

if you're using DOMDocument

$xpath = new DOMXpath($yourdomdocumentobject);
$result= $xpath->query("//enclosure/@url");

xpath "//@url" should work too. There are a lot of solution.

amdev
  • 3,010
  • 3
  • 35
  • 47