[英]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.