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 关注
- 105 浏览
添加回答
举报