嘗試將 sms 日志匯入 php 以在 mysql 資料庫中決議。在抓取所有記錄的完整陣列之后,無法決議單個陣列值。
檔案加載,能夠成功列印整個輸入陣列,但 foreach 回圈僅回傳一個結果,而不是全部 13,并且為空。
// Load xml file else check connection
$xml = simplexml_load_file("input.xml") or die("Error: Cannot load file");
$con = json_encode($xml);
$newXML = json_decode($con, true);
print_r($newXML['sms']); //Output: Prints 0-4 lines successfully all together in array
foreach ($newXML['sms'] as $attrib) {
$date = $attrib->date;
$body = $attrib->body;
echo $date . " - " . $body; // test output (fails and returns empty)
//Save Each Separate array line (sms message record) info to Db...
...
XML 檔案布局:
<?xml version="1.0" encoding="UTF-8"?>
<smsgroup>
<sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654339" type="2" body="message 5" read="1" />
<sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654333" type="1" body="sms 4" read="1" />
<sms address="5555555" time="Apr 30, 2022 1:00:00 PM" date="1555987654329" type="1" body="another message 3" read="1" />
<sms address="5555555" time="Apr 30, 2022 1:00:00 PM" date="1555987654324" type="1" body="message 2" read="1" />
<sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654321" type="2" body="message 1" read="1" />
</smsgroup>
uj5u.com熱心網友回復:
試試這個:
foreach ($newXML['sms'] as $attrib) {
$date = $attrib["@attributes"]["date"];
$body = $attrib["@attributes"]["body"];
echo $date . " - " . $body;
}
uj5u.com熱心網友回復:
您可以通過正確使用 SimpleXML 來簡化代碼,而不必對資料進行 json 編碼和解碼......
用于->訪問元素和[]訪問屬性。
$xml = simplexml_load_file('input.xml') or die('Error: Cannot load file');
foreach ($xml->sms as $attrib) {
$date = $attrib['date'];
$body = $attrib['body'];
echo $date . ' - ' . $body; // test output (fails and returns empty)
}
uj5u.com熱心網友回復:
考慮使用LOAD XML. 下面可以作為 PHP 中的任何其他 SQL 命令運行。
假設所有屬性名稱都匹配表名稱(盡管不匹配的名稱會被忽略):
LOAD XML LOCAL INFILE 'input.xml'
INTO TABLE myTable
ROWS IDENTIFIED BY '<sms>';
或者,SET對特定列或不同命名的表名使用區域變數:
LOAD XML LOCAL INFILE 'input.xml'
INTO TABLE myTable (@date, @body)
ROWS IDENTIFIED BY '<sms>'
SET date_column=@date, body_column=@body;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/469515.html
