在http://feeds.feedburner.com/rb286,有许多图像。但是,当我使用simplXmlElement将其转换为xml对象时,我无法看到图像。我的代码:
if (function_exists("curl_init")){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,"http://feeds.feedburner.com/rb286");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data=curl_exec($ch);
curl_close($ch);
//print_r($data); //here i'm able to see the images
$doc=new SimpleXmlElement($data);
print_r($doc); //here i'm not able to see the images
}
有人能告诉我在转换为xml对象后如何访问图像吗?非常感谢。
您必须在<channel>
主标记中的单个<items>
的<content:encoded>
标记之间进行迭代。我将使用xpath方法来选择标记。一旦你得到了你想要的元素,你就可以用字符串操作工具,比如preg_match_all:,从中提取<img>
编辑: 添加了更精细的图像标签匹配,将feedburner和其他cdn中的广告排除在外。
$xml = simplexml_load_string(file_get_contents("http://feeds.feedburner.com/rb286"));
foreach ($xml->xpath('//item/content:encoded') as $desc) {
preg_match_all('!(?<imgs><img.+?src=[''"].*?http://feeds.feedburner.com.+?[''"].+?>)!m', $desc, $>
foreach ($m['imgs'] as $img) {
print $img;
}
}
<content:encoded>
标记是有名称空间的,所以如果你想使用simplexml的内置属性映射,你必须这样处理:
// obtain simplexml object of the feed as before
foreach ($xml->channel->item as $item) {
$namespaces = $item->getNameSpaces(true);
$content = $item->children($namespaces['content']);
print $content->encoded; // use it howevery you want
}
您可以在这里阅读更多关于xpath查询语言的内容。