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

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

问题描述

我正在使用PHP和simpleXML来阅读以下rss feed:

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天全站免登陆