XML RSS Feed解析PHP

时间:2010-04-21 09:57:54

标签: php xml dom rss

使用这样的XML Feed:

<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

2 个答案:

答案 0 :(得分:3)

我个人使用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 />';
}

答案 1 :(得分:1)

查看DOMDocument::getElementByTagNameNS,您可能还希望DOMNode::lookupNamespaceURI使用前缀(例如w)而不是名称空间URI(例如http://rss.weather.com.au/w.dtd)。