【发布时间】: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>
【问题讨论】: