Error Reading XML with namespace in PHP

Asked

Viewed 418 times

2

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

<?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

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

1 answer

3


There’s an answer in stackoverflow which provides a basis for solving your problem. The problem is that the simple load xml extension, cannot parse the namespaces present in your xml. This can be circumvented with the function Children. Putting it all together is:

<?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. Missing put at the end of the file the closure </soap:Envelope>.

  • It worked great! As for closing the tag, I must have forgotten when copying the xml content. Because mine is closed.

Browser other questions tagged

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