繁体   English   中英

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

[英]php: displaying titles and images of rss feed using xPath

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

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 feed:

<?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 feed。 方法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.'/>');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM