Luke Rayner Luke Rayner - 3 months ago 15
PHP Question

SimpleXML only want to pull specific attributes

I am calling an API which has a bunch of data in XML format, here is a bunch of XML data:

<time from="2016-08-19T15:00:00" to="2016-08-19T18:00:00">
<symbol number="802" name="scattered clouds" var="03d"/>
<precipitation/>
<windDirection deg="196.501" code="SSW" name="South-southwest"/>
<windSpeed mps="2.16" name="Light breeze"/>
<temperature unit="celsius" value="28" min="27.75" max="28"/>
<pressure unit="hPa" value="994.95"/>
<humidity value="89" unit="%"/>
<clouds value="scattered clouds" all="32" unit="%"/>
</time>
<time from="2016-08-19T18:00:00" to="2016-08-19T21:00:00">
<symbol number="500" name="light rain" var="10d"/>
<precipitation unit="3h" value="2.999" type="rain"/>
<windDirection deg="235.003" code="SW" name="Southwest"/>
<windSpeed mps="3.06" name="Light breeze"/>
<temperature unit="celsius" value="26.06" min="25.87" max="26.06"/>
<pressure unit="hPa" value="993.86"/>
<humidity value="88" unit="%"/>
<clouds value="scattered clouds" all="48" unit="%"/>
</time>


There is a lot more but that is what I am getting back from my API request. I just want to pull the "temperature value" for times from="....00:00:00" here is an example:

<time from="2016-08-20T00:00:00" to="2016-08-20T03:00:00">


I want to pull the temperature value from this block of XML, I dont care what the date is all I care about is that the time is 00:00:00.

I have tried to call a regular expression of "/00:00:00/" from an array I put all the data in, I know this isnt the best way either you can probably pull it straight from the xml instead of pulling the xml then putting it in an array it seem pointless to do that!

Here is the code:

<!DOCTYPE html>
<html>

<head>
<title>Open Weather API</title>
</head>

<body>
<?php
$url3hours = "http://api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml&appid=Key";

$xml3hours = simplexml_load_file($url3hours);

$test[] = $xml3hours->forecast;

if (preg_match('/00:00:00/',$test))
{
$temp[] = (string) $xml3hours->forecast->time->temperature["value"];
}

print_r($temp);
?>


</body>

</html>


Sorry if this doesnt make sense I suck at explaining stuff ahah ask any questions if you need to thanks

Answer

Use Xpath to find time tags with from attribute contains T00:00:00

$xml3hours = simplexml_load_file($url3hours);

$list = $xml3hours->xpath('//time[contains(@from, "T00:00:00")]/temperature/@value');

foreach($list as $item) {
  echo $item . "\n";
}
Comments