0

I need to display such info from a rss feed using PHP

Title , Link / url , description and image

I have already done this code below but i am unable to fetch the image from a feed

I checked many site but still yet unable to solve this problem

<?php 

$ch = curl_init("http://economico.sapo.pt/rss/ultimas");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);

$data = curl_exec($ch);
curl_close($ch);

$doc = new SimpleXmlElement($data);
//print_r($doc);

if(isset($doc->channel))
{
    parseRSS($doc);
}
if(isset($doc->entry))
{
    parseAtom($doc);
}

function parseRSS($xml)
{


  // echo "<strong>".$xml->channel->title."</strong>";
    $cnt = count($xml->channel->item);
    for($i=0; $i<$cnt; $i++)
    {
    $postdate = $xml->channel->item[$i]->pubDate;
    //pubDate



    $url    = $xml->channel->item[$i]->link;
    $title  = $xml->channel->item[$i]->title;
    $desc = $xml->channel->item[$i]->description;

    echo $postdate."<br/>".'<a href="'.$url.'">'.$title.'</a><br/>'.$desc.'<br/>';

    }
}

function parseAtom($xml)
{
    echo "<strong>".$xml->author->name."</strong>";
    $cnt = count($xml->entry);
    for($i=0; $i<$cnt; $i++)
    {
    $urlAtt = $xml->entry->link[$i]->attributes();
    $url    = $urlAtt['href'];
    $title  = $xml->entry->title;
    $desc   = strip_tags($xml->entry->content);

    echo '<a href="'.$url.'">'.$title.'</a>'.$desc.'';
    }
}


?>
Kevin
  • 41,694
  • 12
  • 53
  • 70
user3040570
  • 392
  • 3
  • 16

1 Answers1

1

You are already on that right track with using ->attributes(), with regards to those with namespaces, just use ->children(). Simple example:

$url = 'http://economico.sapo.pt/rss/ultimas';
$rss = simplexml_load_file($url, null, LIBXML_NOCDATA);

foreach($rss->channel->item as $item) {
    $title = (string) $item->title;
    $link = (string) $item->link;
    $description = (string) $item->description;
    $pubDate = (string) $item->pubDate;

    $media_image_url = '';
    $media_title = '';
    $media = $item->children('media', 'http://search.yahoo.com/mrss/');
    if(isset($media->content)) {
        $media_image_url = (string) $media->content->attributes()->url;
        $media_title = (string) $media->content->title;
    }

    echo "
        Title: $title <br/> 
        Link: $link <br/> 
        Description: $description <br/> 
        Pub Date: $pubDate <br/>
        Image URL: $media_image_url <br/>
        Media Title: $media_title <br/>
        <hr/>
    ";
}

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70