2 回答

TA貢獻1780條經驗 獲得超1個贊
您在腳本結束時遇到了一些問題,您需要將設備添加到主循環內的數組中,但在所有循環結束后輸出 JSON(您在第一個循環結束時返回數據) .
// loop over Products -> Product item in the xml file
$devices = array();
foreach($simpleXml->Products->Product as $product)
{
$device = array();
foreach($product as $key => $value)
{
//$device[(string)$rewriteKeys[$key]] = (string)$value;
$device[(string)$key] = (string)$value;
}
// unset empty and extra keys after transferring all values
unset($device['epg']);
unset($device[null]);
// Add device into array inside loop
$devices[] = $product;
}
// Return data after processing all product in loop
return stripslashes(json_encode($devices, JSON_PRETTY_PRINT)); // returns a string with JSON object

TA貢獻1155條經驗 獲得超0個贊
你錯過了}第一個結束foreach。因此return總是在 first 的第一個循環內執行foreach:
function XMLtoJSON($xml) {
$xml = file_get_contents($xml); // gets XML content from file
$xml = str_replace(array("\n", "\r", "\t"), '', $xml); // removes newlines, returns and tabs
// replace double quotes with single quotes, to ensure the simple XML function can parse the XML
$xml = trim(str_replace('"', "'", $xml));
$simpleXml = simplexml_load_string($xml);
// loop over Products -> Product item in the xml file
$devices = array();
foreach($simpleXml->Products->Product as $product)
{
$device = array();
foreach($product as $key => $value)
{
//$device[(string)$rewriteKeys[$key]] = (string)$value;
$device[(string)$key] = (string)$value;
// unset empty and extra keys
unset($device['epg']);
unset($device[null]);
}
$devices[] = $product;
} // THIS WAS MISSING
return stripslashes(json_encode($devices, JSON_PRETTY_PRINT)); // returns a string with JSON object
}
- 2 回答
- 0 關注
- 139 瀏覽
添加回答
舉報