使用PHP解析来自weatherstation的数据[重复]

This question already has an answer here:

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 :)

</div>

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)
}