XML RSS订阅解析PHP
问题描述:
,象这样的XML饲料:XML RSS订阅解析PHP
<w:current temperature="22.2" dewPoint="12.9" humidity="56" windSpeed="5.6" windGusts="9.3" windDirection="ESE" pressure="1017.8" rain="0.0" />
和
<w:forecast day="Thursday" description="Mostly Sunny. Warm." min="17" max="29" icon="2" iconUri="http://www.weather.com.au/images/icons/2.gif" iconAlt="Mostly Sunny" />
如何使用DOM我解析它在PHP?
$doc = new DOMDocument();
$doc->load('http://rss.weather.com.au/sa/adelaide');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
$itemRSS = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'description' => $node->getElementsByTagName('w')->item(0)->nodeValue,
);
array_push($arrFeeds, $itemRSS);
}
返回错误:Notice: Trying to get property of non-object in /var/www/index.php on line 123
答
我个人使用SimpleXML对于这一点,你就必须牢记正在使用携带气象数据的自定义空间,这里有一个小例子(带没有错误处理等),我刚刚测试并获取当前的天气。
//Fetch the feed
$feed = file_get_contents("http://rss.weather.com.au/sa/adelaide");
//Load it into simplexml
$weather = simplexml_load_string($feed);
//Get namespace descendants using the w namespace defined in the feed
$channelelements = $weather->channel->item->children("http://rss.weather.com.au/w.dtd");
//Looping through each of the attributes and echoing them, you can do what you want with them at this point
foreach($channelelements->attributes() as $k => $attr) {
echo $k.' = '.$attr.'<br />';
}
答
查找到DOMDocument::getElementByTagNameNS,你可能也需要DOMNode::lookupNamespaceURI的前缀(如w
),而不是命名空间URI(例如http://rss.weather.com.au/w.dtd
)工作。