我正在使用此代码将JSON转换为XML,一切正常。我在XML中获得了200条记录,但我想将其限制为50.我只想创建最新50条记录的XML文件。而不是将JSON中的任何内容转换为XML。
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$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/jsonfile.json");
$json_data = json_decode($json_file, true);
$json_data = array_slice((array)$json_data, 0, 50);
array_to_xml($json_data,$xml_data);
$result = $xml_data->asXML('/directory/xmlfile.xml');
这是我的日期节点的样子:
<dateLastModified>1493913962397</dateLastModified>
<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>
<lastName>xyz</lastName>
<email>abc@xyz.ca</email>
</clientContact>
<isOpen>1</isOpen>
<isPublic>1</isPublic>
<isJobcastPublished>1</isJobcastPublished>
<owner>
<id>222</id>
<firstName>testname</firstName>
<lastName>testlastname</lastName>
<address>
<address1>test address,</address1>
<address2>test</address2>
<city>City</city>
<state>state</state>
<zip>2222</zip>
<countryID>22</countryID>
<countryName>Country</countryName>
<countryCode>ABC</countryCode>
</address>
<email>test@test.com</email>
<customText1>test123</customText1>
<customText2>testxyz</customText2>
</owner>
<publicDescription>
<p>test info</p>
</publicDescription>
<status>test</status>
<dateLastModified>22222</dateLastModified>
<customText4>test1</customText4>
<customText10>test123</customText10>
<customText11>test</customText11>
<customText16>rtest</customText16>
<_score>123</_score>
</item0>
<item1>
...
</item1>
...
</data>
</data>
答案 0 :(得分:1)
很大程度上取决于您对数据的控制程度。如果您可以按时间戳对数据进行排序,那么您可以添加计数器并在计数器达到50时退出循环。
function array_to_xml( $data, &$xml_data ) {
$count = 0;
foreach( $data as $key => $value ) {
$count++;
if($count == 50) {
exit; //or return;
}
if( is_numeric($key) ){
$key = 'item'.$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/jsonfile.json");
$json_data = json_decode($json_file, true);
array_to_xml($json_data,$xml_data);
$result = $xml_data->asXML('/directory/xmlfile.xml');