0

I just found a XML file with weather station data placed on local school - finally I got a source to get local weather.

Please check the file structure http://www.zsvelkebilovice.cz:40010/xml.xml

It's kinda crazy, because there aren't tags named by sensors, but tags with another option .

Is there any option to parse XMLs like this? Same format uses Day One iOS app to store entries in diary - date, weather, GPS and another data arent in specific tags but in tags option.

And I suppose there is a PHP parser which makes me able to access data by $xml->wario->input->sensor->temperature ? Because the only one solution without parser like this is to count the sensor order and acces it by $wario->input->sensor[order] and I can't be use if they don't change the order of tags (or add / delete some).

I can create my own parser but I still think there is a library for this :)

Northys
  • 1,305
  • 3
  • 16
  • 32
  • Hi, yeah this looks pretty straightforward to do with a XML parser that will give you the data in the format you show. – Pekka Dec 21 '13 at 16:18
  • I will check it, thank you guys. When I'm searching I always forget to use simple keywords like "XML in PHP" :D – Northys Dec 21 '13 at 16:41
  • I will have to use XPath right? Or how can I find tag with sensor I want? – Northys Dec 21 '13 at 17:03

1 Answers1

1

You're using SimpleXML at the moment. SimpleXML has a method xpath() that allows you to fetch elements. This encapsulates the Xpath object from DOM. DOMXpath::evaluate() allows you to extract the values directly.

// stripped down xml for testing
$xml = <<<'XML'
<wario><input>
  <sensor>
   <type>humidity</type><id>1011</id><name>Humidity</name><value>100.0</value>
  </sensor>
  <sensor>
    <type>pressure</type><id>1012</id><name>Pressure</name><value>1011.0</value>
  </sensor>
  <sensor>
    <type>temperature</type><id>1025</id><name>T285b30061</name><value>-0.4</value>
  </sensor>
</input></wario>
XML;

// some bootstrap    
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

// fetch the value of the first temperature sensor
$temperature = $xpath->evaluate('number(//sensor[type = "temperature"]/value)');

// fetch sensors with the id 1011
$sensors = $xpath->evaluate('//sensor[id = 1011]');
// get the first one
$sensor = $sensors->item(0);
// get some data from the sensor node
$data = array(
 'type' => $xpath->evaluate('string(type)', $sensor),
 'name' => $xpath->evaluate('string(name)', $sensor),
 'value' => $xpath->evaluate('number(value)', $sensor)
);

var_dump($temperature, $data);

Output:

float(-0.4)
array(3) {
  ["type"]=>
  string(8) "humidity"
  ["name"]=>
  string(8) "Humidity"
  ["value"]=>
  float(100)
}
ThW
  • 19,120
  • 3
  • 22
  • 44
  • Thank you! I wanted something else but I think it doesn't exist and the solution is XPath. I will read more about it. +1 – Northys Dec 21 '13 at 17:32