Search code examples
phpxmlsimplexml

PHP simplexml_load_file not parsing


As you can see I've checked some other answers here on Stackoverflow but I only get blank results. Here's what I've got so far:

$city = simplexml_load_file('http://api.openweathermap.org/data/2.5/weather?q=Tijuana&mode=xml&appid=12fcd235af3a27a895aecb26bc957055');

echo $city['current']['city']['name'];
echo $city->current->city;

Any help is greatly appreciated.


Solution

  • In your code change this:

    $base_clima->wind["speed"]['value'];
    

    This:

    $base_clima->wind->speed['value'];
    

    Sample print of an object:

    [wind] => SimpleXMLElement Object
             (
                [speed] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [value] => 1.95
                                [name] => Light breeze
                            )
    
                    )
             )
    

    For accessing the elements of an object You can use something like this $object->element1->element2 but in simplexml_load_string/file @attributes can be accessed as an array so you can use it like this.

    Try this, Hope this one will be helpful.

    $city = simplexml_load_file('http://api.openweathermap.org/data/2.5/weather?q=Tijuana&mode=xml&appid=12fcd235af3a27a895aecb26bc957055');
    echo $humedad = (string)$city->humidity["value"]; 
    echo $wind_v = (string)$city->wind->speed['value'];