繁体   English   中英

从多级标记的xml中提取数据

[英]Extract data from multi level tagged xml

我从多标签的xml文件中检索数据时遇到问题。 这是xml的示例:

 <forecast5day>
     <city>Өлгий</city>
     <data>
     <weather>
      <date>2018-10-27</date>
      <temperatureNight>-7</temperatureNight>
      <temperatureDay>7</temperatureDay>
      <phenoIdNight>7</phenoIdNight>
      <phenoNight>Багавтар үүлтэй</phenoNight>
      <phenoIdDay>5</phenoIdDay>
      <phenoDay>Багавтар үүлтэй</phenoDay>
      <windNight>5</windNight>
      <windDay>6</windDay>
     </weather>
    </forecast5day>

和我的PHP示例

<?php
    include 'includes/config.php'; // Initialize db;
    $url = "http://tsag-agaar.gov.mn/forecast_xml";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    // Getting data
    $data = curl_exec($ch);
    curl_close($ch);

    global $conn; // Creating connection

    $xml = simplexml_load_string($data);

    foreach ($xml -> forecast5day as $row) {
        var_dump($xml-> forest5day);
        $city = $row -> city;
        $date = $row -> date;
        $temperatureNight = $row -> temperatureNight;
        $temperatureDay = $row -> temperatureDay;
        $phenoIdNight = $row -> phenoIdNight;
        $phenoNight = $row -> phenoNight;
        $phenoIdDay = $row -> phenoIdDay;
        $phenoDay = $row -> phenoDay;
        $windNight = $row -> windNight;
        $windDay = $row -> windDay;
        $sql = "INSERT INTO weather(city,wdate,temperatureNight,temperatureDay,phenoIdNight,phenoNight,phenoIdDay,phenoDay,windNight,windDay) VALUES ('{$city}','{$date}','{$temperatureNight}','{$temperatureDay}','{$phenoIdNight}','{$phenoNight}','{$phenoIdDay}','{$phenoDay}','{$windNight}','{$windDay}')";


        $result = $conn -> query($sql);
        if(!$result) {
            echo "MYSQL Error: $sql <br/>";
        } else {
            echo "SUCCES: $sql <br/>";
        }
    }
?>

以上是我的摘要:

INSERT INTO weather(city,wdate,temperatureNight,temperatureDay,phenoIdNight,phenoNight,phenoIdDay,phenoDay,windNight,windDay) VALUES ('Өлгий','','','','','','','','','')

我做错了什么 ? 除了city我无法获得其他价值。 有什么建议吗?

首先,它不是有效的XML。 没有结束</data>标记。 但是,那可能只是您的帖子,并且代码很好。 该结构表明以下方法将起作用:

$temperatureDay = $row->data->weather->temperatureDay;

当有多个weather要素时, weather成为一个数组。

foreach ($row->data->weather as $weather) {
    $temperatureDay = $weather->temperatureDay;
    // and the other values
}

您是否缺少示例XML中的</data>标签?

由于您试图从“日期”,“温度”等中读取的信息嵌套在“天气”标签中,因此您需要在“行”中向下钻取一个级别:

$row->weather[0]->date

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM