php - 我的 json 对象只输出一个对象,但我的 xml 文件中有更多对象
问题描述
这是我的 JSON 输出,我会喜欢更多对象
[
{
"EcommerceProductGuid": "1282174A-F6A9-4049-8C03-EFDBF065A22F",
"ProductNumber": "-004394",
"Description": "Sparta Ion DLI D50",
"Type": "Ion DLI M-Gear",
"Kind": "Elektrische fiets",
"Brand": "Sparta",
}
]
这是我的 PHP
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;
return stripslashes(json_encode($devices, JSON_PRETTY_PRINT)); // returns a string with JSON object
}
问题是他只输出一个 Product 对象,但我的 XML 文件包含其中 4 个。
解决方案
您在脚本结束时遇到了一些问题,您需要将设备添加到主循环内的数组中,但在所有循环结束后输出 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
推荐阅读
- python - 在 python 2.7 中合并两个字典
- php - php将数组内的空值转换为空白(“”)
- linq - Linq 加入 2 个表并为这两个表使用 contains
- c++ - Qt Creator 无法启动 cdb 调试器
- html - TYPO3 name of language file?
- java - 如何整体导出依赖项?
- mongodb - 在 Redash 中更新 Mongo 文档的查询
- amazon-web-services - 安装 Boto3 AWS EMR 尝试下载引导操作失败
- prolog - Prolog中解决农民山羊狼和白菜问题的优化
- php - PHP 不会通过 POST 传递变量