使用 SimpleXML 读取 RSS 提要 [英] Using SimpleXML to read RSS feed

查看:40
本文介绍了使用 SimpleXML 读取 RSS 提要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP 和 simpleXML 阅读以下 rss 提要:

I am using PHP and simpleXML to read the following rss feed:

http://feeds.bbci.co.uk/news/england/rss.xml

我可以像这样获得大部分我想要的信息:

I can get most of the information I want like so:

$rss = simplexml_load_file('http://feeds.bbci.co.uk/news/england/rss.xml');

echo '<h1>'. $rss->channel->title . '</h1>';

foreach ($rss->channel->item as $item) {
   echo '<h2><a href="'. $item->link .'">' . $item->title . "</a></h2>";
   echo "<p>" . $item->pubDate . "</p>";
   echo "<p>" . $item->description . "</p>";
} 

但是我将如何输出以下标签中的缩略图:

But how would I output the thumbnail image that is in the following tag:

<media:thumbnail width="66" height="49" url="http://news.bbcimg.co.uk/media/images/51078000/jpg/_51078953_226alanpotbury.jpg"/>  

推荐答案

SimpleXML 在处理命名空间方面非常糟糕.您有两种选择:最简单的方法是简单地将提要的内容读入一个字符串并替换命名空间;

SimpleXML is pretty bad at handling namespaces. You have two choices: The simplest hack is to simply read the contents of the feed into a string and replace the namespaces;

$feed = file_get_contents('http://feeds.bbci.co.uk/news/england/rss.xml');
$feed = str_replace('<media:', '<', $feed);

$rss = simplexml_load_string($feed);
...

现在您可以直接访问元素thumbnail.

Now you can access the element thumbnail directly.

更优雅的(不是真的)方法是找出命名空间使用的 URI.如果您查看 http://feeds.bbci.co.uk 的源代码/news/england/rss.xml 你看到它指向http://search.yahoo.com/mrss/.

The more elegant (not really) method is to find out what URI the namespace uses. If you look at the source code for http://feeds.bbci.co.uk/news/england/rss.xml you see that it points to http://search.yahoo.com/mrss/.

现在您可以在 SimpleXMLElement 的 children() 方法中使用此 URI 来获取 media:thumbnail 元素的内容;

Now you can use this URI in the children() method of a SimpleXMLElement to get the contents of the media:thumbnail element;

$rss = simplexml_load_file('http://feeds.bbci.co.uk/news/england/rss.xml');

foreach ($rss->channel->item as $item) {
    $media = $item->children('http://search.yahoo.com/mrss/');
    ...
}

这篇关于使用 SimpleXML 读取 RSS 提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆