从 XML 获取媒体:缩略图


Getting media:thumbnail from XML

我似乎无法解决这个问题。我想从 RSS 文件 (http://feeds.bbci.co.uk/news/rss.xml( 中获取媒体:缩略图。

我做了一些研究,并试图从https://stackoverflow.com/questions/6707315/getting-xml-attribute-from-mediathumbnail-in-bbc-rss-feed和其他来源。

这就是我得到的:

$source_link = "http://feeds.bbci.co.uk/news/rss.xml";
$source_xml = simplexml_load_file($source_link);
$namespace = "http://search.yahoo.com/mrss/";
foreach ($source_xml->channel->item as $rss) {
    $title          = $rss->title;
    $description    = $rss->description;
    $link           = $rss->link;
    $date_raw       = $rss->pubDate;
    $date           = date("Y-m-j G:i:s", strtotime($date_raw));
    $image          = $rss->attributes($namespace);
    print_r($image);
}

当我运行脚本时,我看到的只是一个白页。如果我回显或print_r任何其他变量,那么它就像一个魅力。这只是$image带来问题的问题。为什么这不起作用?感谢任何帮助!

好的,它现在可以工作了。我替换了

$image = $rss->attributes($namespace); 

$image = $rss->children($namespace)->thumbnail[1]->attributes();
$image_link = $image['url'];

它现在就像一个魅力。

此博客的基础,帖子标题 处理媒体:使用 php 的 RSS 提要中的缩略图。

我发现最有效的解决方案是将 xml 文件加载为字符串,然后找到并将"media:thumbnail"替换为格式正确的"缩略图",最后用 simplexml_load_string 将其转换回 xml:

$xSource = 'http://feeds.bbci.co.uk/news/rss.xml';
$xsourcefile = file_get_contents( $xSource );
$xsourcefile = str_replace("media:thumbnail","thumbnail",$xsourcefile);
$xml = simplexml_load_string( $xsourcefile );
echo $row['xtitle'] . '<BR>';
foreach ($xml->channel->item as $item) {
echo ':' . $item->title . '<BR>';
echo ':' . $item->thumbnail['url'] . '<BR>';
}
$image          = $rss->attributes($namespace);

这表示"给我这个<item>元素的所有属性,这些属性在媒体命名空间中"。item 元素上没有属性(更不用说媒体命名空间中的任何属性(,因此不返回任何内容。

你想要这个:

$firstimage = $rss->children($namespace)->thumbnail[0];

顺便说一句,当你使用SimpleXML时,当你需要元素的文本值时,你需要小心地将你的SimpleXMLElements转换为字符串。像$rss->title这样的东西是一个SimpleXMLElement,而不是一个字符串。