Search code examples
xmlparsingweather-apiopenweathermap

Displaying API response in HTML


I am learning API's and am a total beginner to the process, any help will be valuable.

I have managed to get the data im looking for as an XML response and have console.logged it in chrome. I am unsure of how to actually access this #document that i see in the console see below code and console printout

<!doctype html>
<html>
<head>

<script>
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.open("GET","http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&mode=xml&APPID=92cc96ecfe265f251d814b66592a7848",false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.responseXML);
var response = xhr.responseXML;
var xmlString = (new XMLSerializer()).serializeToString(response);
if(xhr.status == 200){
document.getElementById("document").innerHTML = xmlString;
}
}
</script>
<meta charset="UTF-8">
<title>Weather API Test</title>
</head>

<body id="body">
<div id="document"></div>
</body>
</html>

And the console displays:

200
OK
#document
  all of the XML is contained in here that I need to access and display

I have searched for an entire weekend and I cannot find a solution that I am able to understand.

Thanks in advance


Solution

  • I managed to figure it out by using PHP and JSON as an alternative - posting below to help others in the same dilemma

    <!doctype html>
    <html>
    <head>
    
    
    
    <meta charset="UTF-8">
    <title>API TEST JSON</title>
    </head>
    
    <body>
    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    	$place = "capetown,za";
    	$json_string = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=$place&units=metric&APPID=API-KEY-GOES-HERE");
    	$parsed_json = json_decode($json_string);
    	$country = $parsed_json->sys->country;
    	$wind = $parsed_json->wind->speed;
    	$city = $parsed_json->name;
    	$temp = $parsed_json->main->temp;
    	$clouds = $parsed_json->weather[0]->description;
    	if($clouds == "clear sky"){
    		echo ("<img src='http://placehold.it/200x200'>");
    	}
    ?>
    
    <table border="1px solid black">
    <tr>
    <td style="color:red;">Country</td>
    <td style="color:red;"><?php echo $country;?></td>
    </tr>
    <tr>
    <td style="color:red;">City</td>
    <td style="color:red;"><?php echo $city;?></td>
    </tr>
    <tr>
    <td style="color:red;">Temperature</td>
    <td style="color:red;"><?php echo $temp;?></td>
    </tr>
    <tr>
    <td style="color:red;">Wind Speed M/S</td>
    <td style="color:red;"><?php echo $wind;?></td>
    </tr>
    <tr>
    <td style="color:red;">Cloudiness</td>
    <td style="color:red;"><?php echo $clouds;?></td>
    </tr>
    </table>
    </body>
    </html>