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

时间:2018-10-26 12:16:01

标签: php 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以外的其他值。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

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

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

$row->weather[0]->date