【问题标题】:PHP - limit the elements while converting JSON to XMLPHP - 在将 JSON 转换为 XML 时限制元素
【发布时间】:2017-06-19 17:03:31
【问题描述】:

我正在使用此代码将 JSON 转换为 XML,它会生成包含 300 多个元素的巨大 XML 文件。如果我可以限制大小并在 XML 中生成 50 条记录,有什么办法吗?

PHP:

function array_to_xml( $data, &$xml_data ) {
    foreach( $data as $key => $value ) {
        if( is_numeric($key) ){
            $key = 'items'.$key; //dealing with <0/>..<n/> issues
        }
        if( is_array($value) ) {
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
$json_file = file_get_contents("directory/abc.json");
$json_data = json_decode($json_file, true);
echo count($json_data['data']);
array_to_xml($json_data2,$xml_data);
$result = $xml_data->asXML('directory/abc.xml');

XML:

<data>
    <total>212</total>
    <start>0</start>
    <count>212</count>
    <data>
        <item0>
            <id>123</id>
            <title>abc-test1</title>
            <clientContact>
                <id>111</id>
                <firstName>abc</firstName>
                ....
            </clientContact>
            ....
        </item0>
        <item1>
        ...
        </item1>
        ...
        ...
        <item300>
        ...
        </item300>
    </data>
</data>

【问题讨论】:

    标签: php json xml limit


    【解决方案1】:

    请试试这个。我在 if 条件下添加了计数器,其中将值检查为数组

    function array_to_xml( $data, &$xml_data ) {
        $counter = 1;
        foreach( $data as $key => $value ) {
            if( is_numeric($key) ){
                $key = 'items'.$key; //dealing with <0/>..<n/> issues
            }
            if( is_array($value) ) {
                if($counter <= 50) {
                    $subnode = $xml_data->addChild($key);
                    array_to_xml($value, $subnode);
                    $counter++;
                }
            } else {
                $xml_data->addChild("$key",htmlspecialchars("$value"));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多