Search code examples
phphttpweather-apiopenweathermap

Parse XML data to a PHP variable


Getting weather data from openweathermap fails. Here is my code:

$xml = new 
SimpleXMLElement(file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=london&mode=xml'));
$country = $xml->code->country;
$city = $xml->code->city;
echo "Country: $country<br/>City: $city"; 

When I echo I don't get anything at all. Help is appreciated!


Solution

  • The proper path to the country and city values are as follows:

    $country = $xml->city->country;
    $city = $xml->city['name'];
    

    You may also need to remove the spaces in your URL, so the complete code would look like:

    $xml = new SimpleXMLElement(file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=london&mode=xml'));
    $country = $xml->city->country;
    $city = $xml->city['name'];
    echo "Country: $country<br/>City: $city"; 
    

    You may want to have a quick look over basic SimpleXML usage.