getElementsByTagName() on a non-object

百般思念 提交于 2019-12-11 19:26:54

问题


I have a PHP error:

Fatal error: Call to a member function getElementsByTagName () on a non-object in /weather /classes/BxWeatherModule.php on line 37

Here's the code:

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

回答1:


Because you failed to load the data with file_get_contents() the DOM structure had nothing hence the error. To solve it you need to check whether the ELEMENT is an object before you request its attributes etc

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



回答2:


This works for me, try this:

<?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";

?>



来源:https://stackoverflow.com/questions/17381364/getelementsbytagname-on-a-non-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!