1
我正在使用此代碼將JSON轉換爲XML,並且一切正常。我在XML中獲得200條記錄,但我想將其限制爲50.我只是想創建包含最新50條記錄的XML文件。而不是將我們在JSON中的任何內容轉換爲XML。將JSON轉換爲XML時限制XML數據 - PHP
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');
XML
這是我迄今爲止節點是什麼樣子:
<dateLastModified>1493913962397</dateLastModified>
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>
<lastName>xyz</lastName>
<email>[email protected]</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>[email protected]</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>
感謝您的快速響應。我應用了你的解決方案,但它沒有奏效。當我回顯$ count時,它正在渲染這個「1234112312344567123412345678567891011 ...」 – orbnexus
您可以嘗試$ count = $ count + 1; –
不..不起作用。我還嘗試將數組限制爲50,然後將它傳遞給aaray_to_xml函數,但沒有對數據進行分片。 $ json_data = json_decode($ json_file,true); $ json_data = array_slice((array)$ json_data,0,50,true); print_r(array_count_values($ json_data)); – orbnexus