vaanipala
vaanipala

Reputation: 1291

php: parsing rss feed using simplexml and xpath

I tried to parse the link on rss feed with images using php.

I tried parsing the rss feed to display images from the enclosure tag. I tried the solution given on that link. But it doesn't work. The element_attributes function has not been defined.

So, I tried to get the images using xPath. The following is my output (empty array):

Array()

on my web server error log.

Can anyone point out on where i'm going wrong? Thank you.

<?php
if (function_exists("curl_init")){
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL, 'http://menmedia.co.uk/manchestereveningnews/news/rss.xml');
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //curl_setopt($ch,CURLOPT_HEADER,0);
$data=curl_exec($ch);


curl_close($ch);


$doc=new SimpleXmlElement($data,LIBXML_NOCDATA);

function getImage($xml){
    $imgs=$xml->xPath('rss/channel/enclosure[@attributes]');
    print_r($imgs);
    /*foreach ($imgs as $image){
        echo $image->url;
    }*/
}
if (isset($doc->channel)) getImage($doc);

} ?>

Upvotes: 1

Views: 4769

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243619

This single XPath expression:

/rss/channel/item/enclosure/@*

Selects all attributes of all enclosure elements that are children of all channel elements that are children of the top rss element.

This is both simpler and much more efficient thatn using:

//channel/item/enclosure

and then finding the attributes in a separate evaluation.

Do remember:

Evaluation of an XPath expression starting with the // pseudo-operator is usually much slower than using a specific path -- because this causes a non-optimizing XPath processor to traverse the whole document.

Upvotes: 1

vaanipala
vaanipala

Reputation: 1291

I got it to work. It is displaying all the images. As Dimitre has suggested, i'm using '/rss/channel/item/enclosure' minus '@*'. The following is my function:

function getImage($xml){
    $encls=$xml->xPath('/rss/channel/item/enclosure'); 
        foreach($encls as $encl) { 
            print_r('<img src='.$encl->attributes()->url.'/>');
            echo('<br>');
            }

}//end function getImage

thank you guys!

Upvotes: 1

$imgs=$xml->xPath('//channel/item/enclosure');
foreach($imgs as $img) {
    var_dump($img->attributes());
}

Upvotes: 1

Related Questions