非对象上的getElementsByTagName()

时间:2013-06-29 14:41:58

标签: php yahoo-api weather

我有一个PHP错误:

  

致命错误:在a上调用成员函数getElementsByTagName()   第37行/ weather /classes/BxWeatherModule.php中的非对象

以下是代码:

function serviceWeatherIndexPage() {
    include("geoipcity.inc");
    include("geoipregionvars.php");
    $ip = $_SERVER['REMOTE_ADDR'];
    $weather_feed = "";
    $pathr= BX_DOL_URL_ROOT;
    $gi = geoip_open("../GeoLiteCity.dat",GEOIP_STANDARD);
    $record = geoip_record_by_addr($gi,$ip);
    geoip_close($gi);
    $city = $record->city;
    if ($city == "") 
        $city = "Sydney";
    $url_post = "http://where.yahooapis.com/v1/places.q('".urlencode($city)."')?appid=foOF4CzV34EFIIW4gz1lx0Ze1em._w1An3QyivRalpXCK9sIXT5de810JWold3ApkdMdCrc-";
    $weather_feed = file_get_contents($url_post);
    $objDOM = new DOMDocument();
    $objDOM->loadXML($weather_feed);
    $woeid = $objDOM->getElementsByTagName("place")->item(0)->getElementsByTagName("woeid")->item(0)->nodeValue;
}

2 个答案:

答案 0 :(得分:0)

由于您未能使用 file_get_contents()加载数据, DOM 结构 nothing 因此错误。要解决此问题,您需要在请求其属性等之前检查ELEMENT 是否为对象

$url_post = "http://where.yahooapis.com/v1/places.q(".var_dump(urlencode($city)).")?appid=foOF4CzV34EFIIW4gz1lx0Ze1em._w1An3QyivRalpXCK9sIXT5de810JWold3ApkdMdCrc-";
$weather_feed = file_get_contents($url_post);
$objDOM = new DOMDocument();
$objDOM->loadXML($weather_feed);
if (is_object($objDOM->getElementsByTagName("place")->item(0))){
    $woeid = $objDOM->getElementsByTagName("place")->item(0)->getElementsByTagName("woeid")->item(0)->nodeValue; 
 }

答案 1 :(得分:-1)

这对我有用,试试这个:

<?php

    $sUrl = "http://where.yahooapis.com/v1/places.q('paris')?appid=foOF4CzV34EFIIW4gz1lx0Ze1em._w1An3QyivRalpXCK9sIXT5de810JWold3ApkdMdCrc-";
    $sXml = file_get_contents($sUrl);

    $oXml = new DOMDocument();
    $oXml->loadXML($sXml);

    try {
        $sWoeid = $oXml
            ->getElementsByTagName('place')->item(0)
            ->getElementsByTagName('woeid')->item(0)
            ->nodeValue;

    } catch (Exception $oException) {
        print 'Malformed XML';
    }

    print "WOEID is $sWoeid";

&GT;