【问题标题】:XML RSS Feed Parse PHPXML RSS 提要解析 PHP
【发布时间】:2010-04-21 09:57:54
【问题描述】:

使用这样的 XML 提要:

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

如何在 PHP 中使用 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);
}

返回错误:Notice: Trying to get property of non-object in /var/www/index.php on line 123

【问题讨论】:

    标签: php xml dom rss


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-23
        • 2012-11-08
        • 2012-04-15
        • 1970-01-01
        • 2016-01-17
        相关资源
        最近更新 更多