【问题标题】:How to get posts images from RSS?如何从 RSS 中获取帖子图片?
【发布时间】:2018-06-27 03:37:32
【问题描述】:

我想从 RSS 源获取帖子缩略图,但代码不包含图像。

看起来像:

<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>

有没有办法获取图片?它们以缩略图的形式出现在新闻页面上。

【问题讨论】:

  • 请发布一些您正在使用的代码

标签: php xml xml-parsing rss feed


【解决方案1】:

但是您还没有发布您的代码简单代码将是这样的: 如有任何困惑,请询问

Documentation at PHP

php 文件

<?php
  $xml =simplexml_load_file('read.xml');
  echo $xml->channel->title;
  echo '<br/>';
  echo $xml->channel->link;  
?>

xml文件(改动了一点只是添加了内容)

<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>

【讨论】:

  • @ashley 有帮助吗
  • 谢谢,但我知道如何获取这些数据,我想获取图像
  • 在原始帖子中,他们都有图像(缩略图),但在每个项目中,图像都不存在
  • 但是你能告诉我图片在哪里或者你在哪个标签里有图片吗???
  • 我说的是这个,不是每个item都存在
【解决方案2】:

如果您想获取帖子的图片,我们可以这样做 - 假设帖子的内容/正文中有一张图片。这就是我要做的。

我创建了一个包来使 xml 解析变得轻而易举。你可以在这里找到它:https://github.com/mtownsend5512/xml-to-array

然后执行以下操作:

$xml = \Mtownsend\XmlToArray\XmlToArray::convert(file_get_contents('https://www.yourrssfeed.com'));

现在你有了一个漂亮的 php RSS 提要数组。

接下来,我们将创建一个辅助函数来从帖子正文中获取第一张图片。我们将使用它作为帖子的特色图片。

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];
}

如果帖子中没有图片,您需要将http://yoursite.com/images/fallback-image.jpg 替换为备用图片的网址。

现在,我们循环浏览帖子:

foreach ($xml['channel']['item'] as $post) {
    $title = $post['title']);
    $link = $post['link'];
    $description = $post['description'];
    $pubDate = $post['pubDate'];
    $image = getPostImage($post["content:encoded"]);
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2013-07-27
    相关资源
    最近更新 更多