Luke Rayner Luke Rayner - 1 year ago 547
HTML Question

SimpleXML storing attributes in an array

My code is sort of working but I'm not getting the output which I want, I literally just want the output "Gentle Breeze" but instead I am getting "SimpleXMLElement Object ( [0] => Gentle Breeze )"

Here is my code:

<title>Open Weather API</title>

$url = "";
$xml = simplexml_load_file($url);

foreach($xml->forecast->time as $times)
$windspeed[] = $times->windSpeed["name"];


I have tried using echo instead of print_r but all that gets outputted is "Array"

Here is an example of the XML I am pulling from the API:

<time day="2016-08-19">
<symbol number="500" name="light rain" var="10d"/>
<precipitation value="2.97" type="rain"/>
<windDirection deg="188" code="S" name="South"/>
<windSpeed mps="5.28" name="Gentle Breeze"/>
<temperature day="22.58" min="17.06" max="22.58" night="18.39" eve="18.61" morn="17.06"/>
<pressure unit="hPa" value="1012.32"/>
<humidity value="72" unit="%"/>
<clouds value="overcast clouds" all="92" unit="%"/>

I need to store it in an array so I can call it later on in my code, I'm just outputting the results as a test to see what is stored in the array and I just want it to store "Gentle Breeze" not "SimpleXMLElement Object ( [0] => Gentle Breeze )"

Answer Source

A simple cast to string should achieve what you want:

foreach($xml->forecast->time as $times)
    $windspeed[] = (string) $times->windSpeed["name"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download