简体   繁体   中英

XML RSS Feed Parse PHP

With an XML feed like so:

<w:current temperature="22.2" dewPoint="12.9" humidity="56" windSpeed="5.6" windGusts="9.3" windDirection="ESE" pressure="1017.8" rain="0.0" />

and

<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" />

How do I parse it in PHP using the dom?

$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);
}

Returns error : Notice: Trying to get property of non-object in /var/www/index.php on line 123

I'd personally use SimpleXML for this, you just have to bear in mind the custom namespace which is being used to carry the weather data, here's a little example (with no error handling etc) which I've just tested and fetches the current weather.

//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 )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM