XML RSS源解析PHP [英] XML RSS Feed Parse PHP

查看:86
本文介绍了XML RSS源解析PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这样的XML Feed:

With an XML feed like so:

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

< w:forecast day =Thursdaydescription =Most Sunny,Warm。 min =17max =29icon =2iconUri =http://www.weather.com.au/images/icons/2.gificonAlt =Mostly Sunny/>

如何使用dom在PHP中解析?

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

返回错误:注意:试图获取属性非对象在第123行的/var/www/index.php中

推荐答案

亲自使用 SimpleXML ,您只需要牢记自定义命名空间这是用于携带天气数据,这里有一个例子(没有错误处理等),我刚刚测试并获取当前的天气。

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 />';
}

这篇关于XML RSS源解析PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆