在PHP Geonames时区中回显状态消息

15

我正在使用以下PHP代码获取时区:

$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
        $xml = simplexml_load_file($url);

        foreach($xml->children() as $timezone)
        {


            echo "TimezoneId: ".$timezone->timezoneId." ";
            echo "DstOffset : ".$timezone->dstOffset." ";
            echo "GmtOffset : ".$timezone->gmtOffset." ";

}

它可以工作,但是对于南极洲的纬度和经度,例如会返回错误状态消息:

<status message="no timezone information found for lat/lng" value="15"/>

如何输出这个消息?

我正在尝试这样做:

if ($xml->status) {
    echo "error: ".$timezone->status['message']. "";


         }

但不起作用

2个回答

9
您正在尝试从不存在的对象中获取元素。在这样的XML元素中,您有属性和一些值,例如您的情况下:countryCode,countryName,dstOffset,gmtOffset等。如果您使用var_dump(),则可以看到错误消息在这些属性中,这是一个数组。
以下是示例:
在没有问题的位置上使用var_dump():
object(SimpleXMLElement)#4 (12) {
  ["@attributes"]=>
  array(1) {
    ["tzversion"]=>
    string(11) "tzdata2014i"
  }
  ["countryCode"]=>
  string(2) "KG"
  ["countryName"]=>
  string(10) "Kyrgyzstan"
  ["lat"]=>
  string(7) "40.4246"
  ["lng"]=>
  string(7) "74.0021"
  ["timezoneId"]=>
  string(12) "Asia/Bishkek"
  ["dstOffset"]=>
  string(3) "6.0"
  ["gmtOffset"]=>
  string(3) "6.0"
  ["rawOffset"]=>
  string(3) "6.0"
  ["time"]=>
  string(16) "2015-07-09 19:53"
  ["sunrise"]=>
  string(16) "2015-07-09 05:41"
  ["sunset"]=>
  string(16) "2015-07-09 20:36"
}

以下是Antarctica的var_dump():

object(SimpleXMLElement)#4 (1) {
  ["@attributes"]=>
  array(2) {
    ["message"]=>
    string(41) "no timezone information found for lat/lng"
    ["value"]=>
    string(2) "15"
  }
}

您可以轻松地处理和打印此错误消息,如下所示:
if ($xml->status) {
    echo 'error:' . $timezone->attributes()->message;
}

2
尝试这个:
<?php
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach ($xml->geoname as $o_location){
printf(
    'Name %s<br>
    lat is %s<br>
    lon is %s<br>
    geonameId is %s<br>
    countryCode is %s<br>
    countryName is %s<br>
    fcl is %s<br>
    fcode is %<br>
    ',
    $o_location->name,
    $o_location->lat,
    $o_location->lng,
    $o_location->geonameId,
    $o_location->countryCode,
    $o_location->countryName,
    $o_location->fcl,
    $o_location->fcode
);
}
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接