簡體   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