Rather than trying to read the whole document element by element, you can with XMLReader
ask it to import segments.
In this example code, once you get to the <CLIENTE>
level, it reads all of the elements of that level into a SimpleXMLElement (using simplexml_import_dom()
). Once you have done this, you can then process each one using the simpler interface and not have to deal with start and end tags etc...
$xml = new XMLReader();
$xml->open('xml_formatado_stack.xml');
$clientes = array();
$doc = new DOMDocument;
while ($xml->read()) {
if ($xml->nodeType == XMLReader::ELEMENT && $xml->localName == 'CLIENTES') {
while ($xml->read()) {
if ($xml->nodeType == XMLReader::ELEMENT && $xml->localName == 'CLIENTE') {
// Import all child elements into $cl
$cl = simplexml_import_dom($doc->importNode($xml->expand(), true));
// Extract each piece of data, i.e. $cl->CODIGO_INTERESSADO and convert to string to store it
$cliente = [ 'codigo_interessado' => (string)$cl->CODIGO_INTERESSADO,
'nome_interessado' => (string)$cl->NOME_INTERESSADO,
// You will need to complete this bit
];
// Loop across each of the TELEFONE records and store them
foreach ( $cl->TELEFONES->TELEFONE as $telefone ) {
$cliente['telefones'][] = ['numero' => (string)$telefone->NUMERO,
'tipo' => (string)$telefone->TIPO
];
}
// Add the new data to the overall list
$clientes[] = $cliente;
}
}
}
}
This does assume that each <CLIENTE>
isn't very large. You may also have to be careful that the array $clientes
doesn't become too large.