简体   繁体   中英

Getting first image from RSS feed (PHP CURL)

Below code works to pull data from an RSS feed using PHP CURL, however I can't seem to figure out how to get the image URL from the description variable. I just need the first image.

Fatal error: Call to undefined method SimpleXMLElement::description() in      /home/feedolu/public_html/index.php on line 26 

    Function feedMe($feed) {
// Use cURL to fetch text
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, $useragent);
$rss = curl_exec($ch);
curl_close($ch);

// Manipulate string into object
$rss = simplexml_load_string($rss);

$siteTitle = $rss->channel->title;
echo "<h1>".$siteTitle."</h1>";
echo "<hr />";

$cnt = count($rss->channel->item);

for($i=0; $i<$cnt; $i++)
{
    $url = $rss->channel->item[$i]->link;
    $title = $rss->channel->item[$i]->title;
    $desc = $rss->channel->item[$i]->description;
    $image = $rss->channel->item[$i]->description('img', 0);
    echo '<h3><a href="'.$url.'">'.$title.'</a></h3>'.$desc.'';
    echo $image;
}
}

 feedMe("localhost/feed/");

The problem is associated with this link, obviously:

$image = $rss->channel->item[$i]->description('img', 0);

In the context of a SimpleXML class, the description is a property, and not a function. Using the xpath() function to find all <img /> 's makes quick work of the problem.

So, based on your code, here is how I would get the value that you are looking for (even though I don't think your implementation is the best):

$images = $rss->channel->item[$i]->description->xpath('img');
if (count($images) > 0) {
    $image = $images['src'];
}

The solution on this page worked for me:-

How to get first image from a tumlbr rss feed in PHP

$image = '';
if (preg_match('/src="(.*?)"/', $rss->channel->item[$i]->description, $matches)) {
    $image = $matches[1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM