Retrieve XML report data in PHP

Asked

Viewed 1,674 times

3

I have the following report in the XML link: http://api.openweathermap.org/data/2.5/weather?q=qArmaz%C3%A9m,Br&mode=xml

I would just like to treat it in a very simple way, I tried using something like:

<?php
$xml = simplexml_load_string("http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml");
echo $xml->temperature;
?>

But without success. What would be the best way to deal with such a report?

2 answers

3


To access the value in XML you must call the tag name and access the value using foo["value"].
For example, for:

<city id="3469115" name="Armazém">

Stays:

$xml->city["name"];

To read the XML I used the curl as follows:

<?php

function get_data($url) 
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/xml; charset=ISO-8859-1"));
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$xml = get_data("http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml");
$xml = simplexml_load_string($xml);
echo $xml->temperature["value"];
?>
  • Thank you for the answer, solved my problem!

  • Could you just quote how I can get country for example in this xml? I did it like this: || echo $xml->country; || but it doesn’t work.

  • Note that <country> is inside <city> then stay $xml->city->country;.

  • Thanks, it worked!

1

Has the way with file_get_contents.

<?php
    header ('Content-type: text/html; charset=utf-8');
    $data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=Armazem,SC&mode=xml');
    $xml  = simplexml_load_string($data);

    $cityID       = $xml->city['id'];
    $cityName     = $xml->city['name'];
    $cityCoordLon = $xml->city->coord['lon'];
    $cityCoordLat = $xml->city->coord['lat'];
    $cityCountry  = $xml->city->country;
    $citySunRise  = $xml->city->sun['rise'];
    $citySunSet   = $xml->city->sun['set'];

    $temperatureValue = $xml->temperature['value'];
    $temperatureMin   = $xml->temperature['min'];
    $temperatureMax   = $xml->temperature['max'];
    $temperatureUnit  = $xml->temperature['unit'];

    $humidityValue = $xml->humidity['value'];
    $humidityUnit  = $xml->humidity['unit'];

    $pressureValue = $xml->pressure['value'];
    $pressureUnit  = $xml->pressure['unit'];
  • 1

    Thanks for your cooperation too!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.