繁体   English   中英

php geonames timezone中的回显状态消息

[英]Echo status message in php geonames timezone

我正在使用以下代码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." ";

}

它工作但是对于Antartica的纬度和经度,例如它给出错误状态消息:

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

如何回应这条消息?

我试试这个:

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


         }

但是不行

您正试图从对象中获取一个不存在的元素。 在这样的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"
}

这里有一个Antartica的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;
}

试试这个,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM