【发布时间】:2011-12-29 10:11:54
【问题描述】:
我正在尝试为以下 rss 提要提取 rss 提要 http://menmedia.co.uk/manchestereveningnews/news/rss.xml
我可以用这个方法解决这个问题:
<?
$xml = file_get_contents('http://menmedia.co.uk/manchestereveningnews/news/rss.xml');
// Use cURL to get the RSS feed into a PHP string variable.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://menmedia.co.uk/manchestereveningnews/news/rss.xml');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
// Include the handy XML data extraction functions.
include 'xml_regex.php';
// An RSS 2.0 feed must have a channel title, and it will
// come before the news items. So it's safe to grab the
// first title element and assume that it's the channel
// title.
$channel_title = value_in('title', $xml);
// An RSS 2.0 feed must also have a link element that
// points to the site that the feed came from.
$channel_link = value_in('link', $xml);
// Create an array of item elements from the XML feed.
$news_items = element_set('item', $xml);
foreach($news_items as $item) {
$title = value_in('title', $item);
$url = value_in('link', $item);
$description = value_in('description', $item);
$timestamp = strtotime(value_in('pubDate', $item));
$item_array[] = array(
'title' => $title,
'url' => $url,
'description' => $description,
'timestamp' => $timestamp
);
}
if (sizeof($item_array) > 0) {
// First create a div element as a container for the whole
// thing. This makes CSS styling easier.
$html = '';
// Markup the title of the channel as a hyperlink.
$html .= '';
// Now iterate through the data array, building HTML for
// each news item.
$count = 0;
echo "";
foreach ($item_array as $item) {
$html .= '<a href="'.make_safe($item['url']).'" target="_blank">
<img src="'.$item['enclosure'].'">
'.substr("".$item['title']."", 0, 80).'
</div></a>';
echo '';
// Limit the output to five news items.
if (++$count == 1) {
break;
}
}
$html .= '';
echo $html;
}
function make_safe($string) {
$string = preg_replace('#<!\[CDATA\[.*?\]\]>#s', '', $string);
$string = strip_tags($string);
// The next line requires PHP 5, unfortunately.
//$string = htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
// Instead, use this set of replacements in PHP 4.
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = str_replace('(', '(', $string);
$string = str_replace(')', ')', $string);
return $string;
}
?>
但是,我试图让图片也可以通过 rss 提要的附件标签中的图片。
在我使用的那一刻:
<img src="'.$item['enclosure'].'">
这行不通。
任何想法都将不胜感激!
谢谢
【问题讨论】:
-
你能打印_r $item 看看它有什么吗?
-
这不适用于我正在使用的编码
-
如果我可以问@meohmy 为什么?在 foreach 中只需编写 print_r($item) 即可获得 $item 元素的结构。