Error Reading XML with namespace in PHP

1

I need to access the value of the numeroCNS , dataAtribuicao , etc tags of the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <cad:responseConsultar xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice">
        <usu:UsuarioSUS xmlns:usu="http://servicos.saude.gov.br/schema/cadsus/v5r0/usuariosus" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
            <usu:Cartoes>
                <usu:CNS>
                    <cns:numeroCNS xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">foo</cns:numeroCNS>
                    <cns:dataAtribuicao xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">bar</cns:dataAtribuicao>
                    <cns:tipoCartao xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">fubá</cns:tipoCartao>
                    <cns:manual xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">canjica</cns:manual>
                    <cns:justificativaManual xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns" />
                </usu:CNS>
            </usu:Cartoes>
        </usu:UsuarioSUS>
    </cad:responseConsultar>
</soap:Body>
</soap:Envelope>

My code:

<?php
$x = simplexml_load_file('xml/teste.xml');
echo $x -> Body -> responseConsultar -> UsuarioSUS -> Cartoes -> CNS -> 
numeroCNS;
?>
  

PHP Notice: Trying to get property of non-object

If you manually remove namespaces , the code works. But it would be impractical to do this in all XML files. What am I doing wrong?

    
asked by anonymous 14.04.2017 / 03:04

1 answer

2

There is an answer in stackoverflow in English that provides a foundation for solving your problem. The problem is that the simple load xml extension, can not parse the namespaces present in your xml. This can be bypassed with the children function. Putting everything together stays:

<?php
$x = simplexml_load_file('xml/teste.xml');
$campos = $x->children('soap', true)->children('cad', true)->children('usu', true)->UsuarioSUS->Cartoes->CNS->children('cns', true);

foreach($campos as $chave => $valor){
    echo $chave . ' : ' . $valor . '<br>';
}

?>

There is a small error in the xml posted in the question. The closing </soap:Envelope> is missing at the end of the file.

    
14.04.2017 / 06:01