Get XML report data in PHP

3

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:

<?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 handle such a report?

    
asked by anonymous 10.05.2014 / 05:16

2 answers

3

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:

$xml->city["name"];

To read the XML of the url entered I used 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"];
?>
    
10.05.2014 / 05:44
1

Own 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'];
    
11.05.2014 / 03:51