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
. 有什么建议吗?
解决方案
首先,它不是有效的 XML。没有结束</data>
标签。但是,这可能只是您的帖子,并且代码很好。该结构表明以下将起作用:
$temperatureDay = $row->data->weather->temperatureDay;
当有多个weather
元素时,weather
变成一个数组。
foreach ($row->data->weather as $weather) {
$temperatureDay = $weather->temperatureDay;
// and the other values
}
推荐阅读
- r - R`t.test`问题导致`159等于8875`
- python - onedrivesdk 未使用 pip 安装
- amazon-web-services - 如何从 cloudwatch 日志中提取时间值以执行数学运算
- audio - ubuntu 18.04 没有声音
- javascript - 如何使用javascript覆盖ubuntu中的默认cmd快捷键
- java - Joda-time,期间计算问题?
- sage-erp - 如何在 SAGE 中从外部系统创建 IC 内部使用条目?
- angular - 角料表检测滚动
- python-3.x - 尝试在 pycharam 中使用 sys
- javascript - 循环循环 React Material UI Javascript