关于解析xml的几个问题


Couple questions about parsing xml

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

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

<?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 )

我把它缩短了,这样更容易阅读。完整的一个在patriovoice.net上。在上面的代码中,我注意到标题是一个SimpleXMLElement对象,我曾尝试使用print_r($xml->item[0]->title);打印它,但它什么都不打印。我做错了什么,所以我可以有10个<a href="$link">$title</a>

试试这个:

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

您必须将叶值强制转换为String

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

没有强制转换,它们只表示空的SimpleXMLElements。