2017-06-19 4 views
1

J'utilise ce code pour convertir JSON en XML et il en résulte un énorme fichier XML avec 300 éléments plus. Est-il possible si je peux limiter la taille et juste générer 50 enregistrements dans le XML?PHP - limiter les éléments lors de la conversion de JSON en 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> 

Répondre

1

S'il vous plaît essayer. J'ai ajouté le compteur dans sous if si la condition de vérification valeur comme tableau

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