Search code examples
phpjsonxmllimit

PHP - limit the elements while converting JSON to XML


I am using this code to convert JSON to XML and it is resulting huge XML file with 300 plus elements. Is there any way if i can limit the size and just generate 50 records in the XML?

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>

Solution

  • Please try this. I have added the counter in under if condition where checking value as array

    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"));
            }
        }
    }