php:使用xPath显示rss提要的标题和图像


php: displaying titles and images of rss feed using xPath

我正在尝试使用php中的xpath来显示rss提要的标题和图像。但它只显示了一个标题。没有显示所有标题,也没有显示任何图像。我的代码:

function getImage($xml){
    $items=$xml->xPath('/rss/channel/item');
    foreach($items as $item){
        echo($item->title);
        $encl=$xml->xPath('//enclosure');
        print_r('<img src='.$encl->attributes()->url.'/>');
        echo('<br>');
    }

有人能指出我哪里错了吗?非常感谢。

好的,我开始工作了。:)每个标题都会显示一个图像。我的代码:

首先,我使用curl:下载rss提要

<?php
if (function_exists("curl_init")){
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL, 'http://menmedia.co.uk/manchestereveningnews/news/rss.xml');
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //curl_setopt($ch,CURLOPT_HEADER,0);
$data=curl_exec($ch);

curl_close($ch);

$doc=new SimpleXmlElement($data,LIBXML_NOCDATA);

然后我分析rss提要。方法1和方法2都产生相同的输出。

function parseRSS($xml){
    $encl_array=array();
    $x=0;
    $i=0;
    $encls=$xml->xPath('/rss/channel/item/enclosure'); 
        foreach($encls as $encl) { 
            $encl_array[$x]=$encl->attributes()->url;
            $x+=1;
        }
            //method 1
    /*$cnt=count($xml->channel->item);
    for($i=0;$i<$cnt;$i++){
        $title=$xml->channel->item[$i]->title;
        print_r('<img src='.$encl_array[$i].'/>');
        echo $title.'<br>';
    }*/
            //method 2 - using xPath
    $items=$xml->xPath('/rss/channel/item');
    foreach ($items as $item){
        echo('<img src='.$encl_array[$i].'/>');
        echo($item->title.'<br>');
        $i+=1;
    }
}//end function parseRSS
    if (isset($doc->channel)) parseRSS($doc);
}//end if (function_exists("curl_init"))

?>

您可以简单地将其称为

if($item->enclosure)
 print_r('<img src='.$encl->attributes()->url.'/>');