首页 > 解决方案 > 从多级标记的 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. 有什么建议吗?

标签: phpxml

解决方案


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

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

当有多个weather元素时,weather变成一个数组。

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

推荐阅读