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

不问归期 提交于 2019-12-08 12:04:26

问题


0Here is the relevant part of my rss feed:

    <channel>
        <description></description>
        <title>Untitled</title>
        <generator>Tumblr (3.0; @xxx)</generator>
        <link>http://xxx.tumblr.com/</link> 
        <item>
            <title>Title</title>
            <description>&lt;figure&gt;&lt;img src="https://31.media.tumblr.com/c78c7t3abd23423549d3bb0f705/tumblr_inline_nkp9z234d0uj.jpg"/&gt;&lt;/figure&gt;</description>
            <link>http://xxx.tumblr.com/post/99569244093</link>
            <guid>http://xxx.tumblr.com/post/99569244093</guid>
            <pubDate>Thu, 09 Oct 2014 11:19:33 -0400</pubDate>
        </item>
    </channel>

Using the answer from other questions on here I tried this:

$content = file_get_contents("http://xxx.tumblr.com/rss"); 
$feed = new SimpleXmlElement($content); 
$imgs = $feed->channel->item[0]->description->xpath('//img');
    foreach($imgs as $image) {
            echo (string)$image['src'];     
};

This is returning an empty array for $imgs

Does it have something to do with the tags being &lt; &gt; etc?

and if so what can I do?


回答1:


You can get it from the description, which seems to include a HTML image tag for the image, by using a simple regular expression with preg_match:

$content = file_get_contents("http://xxx.tumblr.com/rss");
$feed    = new SimpleXmlElement($content);
$img     = (string)$feed->channel->item[0]->description;

if (preg_match('/src="(.*?)"/', $img, $matches)) {
    $src = $matches[1];
    echo "src = $src", PHP_EOL;
}

Output:

src = http://40.media.tumblr.com/58d24c3009638514325b113859ba369f/tumblr_nk0mwfhKXU1sl87kjo1_500.jpg



回答2:


Before you can use xapth() on the description, you need to create a new XML document out of it:

$url  = "http://xxx.tumblr.com/rss";
$desc = simplexml_load_file($url)->xpath('//item/description[1]')[0];
$src  = simplexml_load_string("<x>$desc</x>")->xpath('//img/@src')[0];

echo $src;

Output:

http://40.media.tumblr.com/58d24c3009638514325b113859ba369f/tumblr_nk0mwfhKXU1sl87kjo1_500.jpg



回答3:


I'm not sure if you can use this approach - as already mentioned by kjhughes as comment, your input XML does not contain any img element. But it's possible to retrieve the image source using XPath substring-functions:

substring-before(substring-after(substring-after(//item/description[contains(.,'img')],
'src='),'"'),'"')

Result:

https://31.media.tumblr.com/c78c7t3abd23423549d3bb0f705/tumblr_inline_nkp9z234d0uj.jpg


来源:https://stackoverflow.com/questions/28862873/how-to-get-first-image-from-a-tumlbr-rss-feed-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!