Filling an Array with Read Data from an XML File

Asked

Viewed 76 times

0

I need to fill an array with read data from an XML file, the code is listing all of the xml file the data in the browser correctly:

if (file_exists('clientes.xml')) {
   $xml = simplexml_load_file('clientes.xml');

   foreach ($xml as $torcedor => $registro) {  
      foreach($registro->attributes() as $k => $valor) {
         echo $k." : ".$valor.' <br />';
      }
   }

} else {
    exit('Falha ao abrir clientes.xml.');
}

But if I remove the line from the code echo $k." : ".$valor.' <br />'; which lists the data in the browser and I put that code $novoArray[$k] = (string)$valor; is filled only the last xml file record in the newArray. The result is like this:

Array (
   [nome] => Dr. Samanta Renata Chaves
   [documento] => 834.881.326-84
   [cep] => 58136-468
   [endereco] => Travessa Pacheco, 0049
   [bairro] => Catarina do Sul
   [cidade] => Vila Amlia
   [uf] => BA
   [telefone] => (81) 2450-0382
   [email] => [email protected]
   [ativo] => 1
 )

But I need to fill the new Image with all the xml file data and exit in the following format below:

    Array (
        0 => Array (    
            [nome] => Dr. Samanta Renata Chaves
            [documento] => 834.881.326-84
            [cep] => 58136-468
            [endereco] => Travessa Pacheco, 0049
            [bairro] => Catarina do Sul
            [cidade] => Vila Amlia
            [uf] => BA
            [telefone] => (81) 2450-0382
            [email] => [email protected]
            [ativo] => 1
        ),
        1 => Array (    
            [nome] => Fulano Siclano da Silva
            [documento] => 834.456.850-02
            [cep] => 73050-468
            [endereco] => Travessa Pacheco, 0049
            [bairro] => Prazeres
            [cidade] => Brasília
            [uf] => DF
            [telefone] => (81) 2450-0382
            [email] => [email protected]
            [ativo] => 1
        )
    )

Does anyone know how to implement this solution?

  • Already tried $newArray[] = (string)$value; ?

  • Yes, but this way does not assign the name to the keys, it is a giant array with numeric keys.

1 answer

1


Test this:

if (file_exists('clientes.xml')) {
   $xml = simplexml_load_file('clientes.xml');

   $novoArray = []; // aqui estou criando um novo array
   $i = 0;          // iniciei um contador

   foreach ($xml as $torcedor => $registro) {
      foreach($registro->attributes() as $k => $valor) {
         $novoArray[$i][$k] = (string)$valor;   // a cada iteração do foreach pai
                                               // ele vai aumentar um indice 
      }

      $i++;         // incrementei um ao contador

   }

} else {
    exit('Falha ao abrir clientes.xml.');
}

I hope I’ve helped!

  • 1

    It worked perfectly José Veiga, thank you very much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.