结合关于解析xml的问题

时间:2013-12-01 15:32:42

标签: php xml

好吧,我真的不明白这个概念,但我不想使用小部件来远离他们的广告。

因此,我试图通过客户广播电台网站为福克斯新闻制作10个全国性的结果。我只想要一个链接,所以我需要从Feed中获取标题和链接。

<?php
$xml=simplexml_load_file("http://feeds.foxnews.com/foxnews/latest");
print_r($xml);

?>

该代码打印此

SimpleXMLElement Object ( [@attributes] => Array ( [version] => 2.0 ) [channel] => 
SimpleXMLElement Object ( [title] => FOXNews.com [link] => http://www.foxnews.com/ [description] => 
FOX News Channel - We Report. You Decide. [copyright] => Copyright 2013 FOX News Channel 
[managingEditor] => foxnewsonline@foxnews.com [language] => en-us [lastBuildDate] => Sun, 01 
December 2013 10:08:27 EST [webMaster] => foxnewsonline@foxnews.com [image] => SimpleXMLElement 
Object ( [url] => http://www.foxnews.com/images/headers/fnc_logo.gif [title] => FOXNews.com Live 
Bookmark [link] => http://www.foxnews.com/ ) [item] => Array ( [0] => SimpleXMLElement Object ( 
[title] => SimpleXMLElement Object ( ) [link] => http://www.foxnews.com/us/2013/12/01/metro-north-
passenger-train-derails-in-nyc-leaving-some-cars-in-water/ [author] => foxnewsonline@foxnews.com 
[description] => SimpleXMLElement Object ( ) [pubDate] => Sun, 01 Dec 2013 09:49:42 EST ) [1] => 
SimpleXMLElement Object ( [title] => SimpleXMLElement Object ( ) [link] => 
http://www.foxnews.com/politics/2013/12/01/obamacare-website-re-do-deadline-set-for-saturday/ 
[author] => foxnewsonline@foxnews.com [description] => SimpleXMLElement Object ( ) [pubDate] => Sun, 
01 Dec 2013 09:49:42 EST )

我缩短了它,因此更容易阅读。完整的是patriotvoice.net。在上面的代码中,我注意到标题是一个SimpleXMLElement对象,我试图使用print_r($xml->item[0]->title);将其打印出来,但它不会打印任何内容。我做错了什么,所以我可以有10 <a href="$link">$title</a>

2 个答案:

答案 0 :(得分:0)

您必须将叶值转换为字符串

var_dump((string)$xml->channel->item[0]->title);

如果没有强制转换,它们只代表空的SimpleXMLElement。

答案 1 :(得分:0)

试试这个:

$link = $xml->channel->item[37]->link;
$title = $xml->channel->item[37]->title;
print "<a href=\"$link\">$title</a>";