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']. "";


         }

但不工作

4

2 回答 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"
}

这里是南极洲的 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;
}
于 2015-07-09T13:59:05.373 回答
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
);
}
?>
于 2015-07-15T18:44:55.540 回答