2 回答
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
您在腳本結(jié)束時(shí)遇到了一些問題,您需要將設(shè)備添加到主循環(huán)內(nèi)的數(shù)組中,但在所有循環(huán)結(jié)束后輸出 JSON(您在第一個(gè)循環(huán)結(jié)束時(shí)返回?cái)?shù)據(jù)) .
// 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貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
你錯(cuò)過了}第一個(gè)結(jié)束foreach。因此return總是在 first 的第一個(gè)循環(huán)內(nèi)執(zhí)行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 關(guān)注
- 150 瀏覽
添加回答
舉報(bào)
