Get XML report data in PHP

Posted on

Question :

I have the following report on the XML link: link

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

$xml = simplexml_load_string(",SC&mode=xml");
echo $xml->temperature;

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


Answer :

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

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

It stays:


To read the XML of the url entered I used curl as follows:


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);
    return $data;

$xml = get_data(",SC&mode=xml");
$xml = simplexml_load_string($xml);
echo $xml->temperature["value"];


Own the way with file_get_contents .

    header ('Content-type: text/html; charset=utf-8');
    $data = file_get_contents(',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'];


Leave a Reply

Your email address will not be published. Required fields are marked *