I want to get posts thumbnails from RSS feeds, But the code doesn't contain the images.
It looks like:
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title></title>
<link></link>
<description>Main feed</description>
<language>is-IS</language>
<pubDate>Wed, 27 Jun 2018 02:47:24 GMT</pubDate>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<ttl>100</ttl>
<generator>RSS</generator>
<item>
<title></title>
<description>
<![CDATA[
]]>
</description>
<link></link>
<guid/>
<pubDate>Tue, 26 Jun 2018 12:00:00 GMT</pubDate>
</item>
</channel>
</rss>
Is there is a way to get the images? They exist on the news page as thumbnails.
However you haven't post your code Simple Code Will be like this: if any confusion please ask
php file
<?php
$xml =simplexml_load_file('read.xml');
echo $xml->channel->title;
echo '<br/>';
echo $xml->channel->link;
?>
xml file(changed little bit just added content)
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
<title>title is here</title>
<link>link is here</link>
<description>Main feed</description>
<language>is-IS</language>
<pubDate>Wed, 27 Jun 2018 02:47:24 GMT</pubDate>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<ttl>100</ttl>
<generator>RSS</generator>
<item>
<title></title>
<description>
<![CDATA[
]]>
</description>
<link></link>
<guid/>
<pubDate>Tue, 26 Jun 2018 12:00:00 GMT</pubDate>
</item>
</channel>
If you are wanting to get the post's image, we can do that - presuming there is an image in the post's content/body. Here's what I would do.
I created a package to make xml parsing a breeze. You can find it here: https://github.com/mtownsend5512/xml-to-array
Then do the following:
$xml = \Mtownsend\XmlToArray\XmlToArray::convert(file_get_contents('https://www.yourrssfeed.com'));
Now you have a nice php array of the rss feed.
Next, we will create a helper function to get the first image out of the post's body. We'll use this as the post's featured image.
function getPostImage($content)
{
$output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $matches);
if (empty($matches[1][0])) {
return 'http://yoursite.com/images/fallback-image.jpg';
}
return $matches[1][0];
}
You'll want to replace http://yoursite.com/images/fallback-image.jpg
with the url to your fallback image if there is no image in the post.
Now, we loop through the posts:
foreach ($xml['channel']['item'] as $post) {
$title = $post['title']);
$link = $post['link'];
$description = $post['description'];
$pubDate = $post['pubDate'];
$image = getPostImage($post["content:encoded"]);
}
Hope that helps.