2012-07-15 49 views
0

我试图在php中使用xpath显示RSS源的标题和图像。但它只显示1个标题。所有标题都不显示,也没有任何图像显示。我的代码: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>'); 
    } 

有人可以指出我哪里出错了吗?谢谢。

+2

提供XML的片段或指向我们的RSS Feed,这样我们就可以回答这个问题。 – 2012-07-15 05:02:29

回答

0

好的,我得到它的工作。 :)每个标题都显示一个图像。我的代码:

首先,我下载使用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")) 


?> 
0

你可以简单地把它作为

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