2015-07-07 17 views
15

Używam następujący kod php, aby uzyskać Strefa czasowa:komunikat stanu Echo w geonames php czasowej

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

} 

to działa, ale dla szerokości i długości geograficznej Antartica na przykład dać błędów Komunikat Status:

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

Jak wyświetlić tę wiadomość?

mam tryng to:

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


     } 

ale nie działają

Odpowiedz

9

Próbujesz uzyskać element z obiektu, który nie istnieje. W takim elemencie XML masz atrybuty i niektóre wartości, jak w twoim przypadku: countryCode, countryName, dstOffset, gmtOffset itd. Jeśli użyjesz var_dump(), wynik zobaczysz, że komunikat o błędzie znajduje się w tych atrybutach, czyli tablicy.

Tutaj jesteś przykładem:

var_dump() na miejscu bez problemu:

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

I tu var_dump() z Antartica:

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

można łatwo obsługiwać i wydrukuj następujący komunikat o błędzie:

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

spróbuj tego,

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