首页 > 解决方案 > 我的 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 个。

标签: phpjsonxml

解决方案


您在脚本结束时遇到了一些问题,您需要将设备添加到主循环内的数组中,但在所有循环结束后输出 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

推荐阅读