2015-07-07 25 views
15

Tôi đang sử dụng sau php code để lấy múi giờ:Echo thông báo trạng thái trong geonames php múi giờ

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

} 

nó hoạt động nhưng đối với vĩ độ và kinh độ của Antartica ví dụ nó cho lỗi thông báo trạng thái:

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

Cách lặp lại thông báo này?

Tôi tryng này:

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


     } 

nhưng không có tác dụng

Trả lời

9

Bạn đang cố gắng để có được một phần tử từ đối tượng, trong đó không tồn tại. Trong phần tử XML như vậy bạn có các thuộc tính và một số giá trị như trong trường hợp của bạn: countryCode, countryName, dstOffset, gmtOffset và vv. Nếu bạn sử dụng var_dump() kết quả bạn có thể thấy thông báo lỗi nằm trong các thuộc tính này, là một mảng.

Ở đây bạn là một ví dụ:

var_dump() trên một vị trí mà không vấn đề:

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

Và đây một var_dump() của Antartica:

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

Bạn có thể dễ dàng xử lý và in thông báo lỗi này như sau:

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

thử này,

<?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 
); 
} 
?> 
Các vấn đề liên quan