Question

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!

Was it helpful?

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.

OTHER TIPS

You are missing all the error message nor are you missing to check function return values before continuing further on:

Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather? q=london&mode=xml): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST

This means your HTTP request has failed because it's a bad request. Check if the URI is correct. If so, contact the API service provider for your support options.

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML'

Your script has a fatal error. It not only does not output anything, it even stopped to halt before it reached it's planned end. That is because you think everything must always work. Instead also check for error messages.

This has been outlined in a previous question here:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top