简体   繁体   中英

Echo status message in php geonames timezone

I'm using following code php to get timezone:

$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." ";

}

it work but for latitude and longitude of Antartica for example it give error status message:

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

How to echo this message?

I'm tryng this:

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


         }

but don't work

You are trying to get an element from object, which doesn't exist. In such a XML element you have attributes and some values like in your case: countryCode, countryName, dstOffset, gmtOffset and etc. If you use var_dump() the result you can see the error message is in these attributes, which is an array.

Here you are an example:

var_dump() on a location without problem:

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

And here a var_dump() of Antartica:

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

You can easily handle and print this error message like that:

if ($xml->status) {
    echo 'error:' . $timezone->attributes()->message;
}

try this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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