dqy92287 2013-12-21 16:13
浏览 38
已采纳

使用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>
  • 写回答

1条回答 默认 最新

  • dso15221 2013-12-21 16:55
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口