Capture SOAP Header with PHP [closed]

2

Good Afternoon

I'm consuming a WSDL from a Webservice where after login and after each XML compliant request returned below I get the following tags in the Soap head

<Sequencia> 1 </ Sequencia>
<SessionId> 4b4uc2536530-941f-44e6-ab95-8ee7179fb016 </ SessionId>
 

As a security rule I must save these and in the next request I use the data for the next request to write, in this new request will be generated new session and sequence and I should save them to another request and so on.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <Sessao xmlns="http://dominio.com.br">
            <Sequencia>1</Sequencia>
            <SessionId>4b4uc2536530-941f-44e6-ab95-8ee7179fb016</SessionId>
            <Versao>
                <Id>1</Id>
                <SituacaoCache>Inalterado</SituacaoCache>
                <VersaoAtual>0</VersaoAtual>
                <ReleaseAtual>0</ReleaseAtual>
                <ProximaAtualizacao>0001-01-01T00:00:00</ProximaAtualizacao>
                <Minutos>0</Minutos>
                <VersaoDisponivel>
                    <VersaoRota>0</VersaoRota>
                    <VersaoBanco>0</VersaoBanco>
                    <ReleaseBanco>0</ReleaseBanco>
                    <Compilacao>0</Compilacao>
                </VersaoDisponivel>
                <QuantidadeReleases>0</QuantidadeReleases>
            </Versao>
        </Sessao>
    </soap:Header>
    <soap:Body>
        <LogOnResponse xmlns="http://dominio.com.br">
            <LogOnResult>
                <Excecoes />
                <DatabaseCount>0</DatabaseCount>
                <Retorno>
                    <Id>18659</Id>
                    <Nome>NOME</Nome>
                    <Email>[email protected]</Email>
                    <Endereco />
                    <Bairro />
                    <Cidade />
                    <Estado />
                    <Pais />
                    <Cep />
                    <LogOn>login</LogOn>
                    <DataNascimento>1984-09-17T00:00:00</DataNascimento>
                    <RG />
                    <Cpf>000.000.000-00</Cpf>
                    <Telefone />
                    <Celular />
                    <Configuracoes />
                    <Ativo>true</Ativo>
                    <Tema>Azul</Tema>
                    <Perfil>
                        <Id>12</Id>
                        <Nome>Sites Externos</Nome>
                        <Descricao />
                        <NiveisAcesso>
                            <CLPerfilNivelAcesso>
                                <Id>11</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <NivelAcesso>
                                    <Id>1</Id>
                                    <Nome>Usuário</Nome>
                                    <Codigo>1</Codigo>
                                    <Descricao />
                                </NivelAcesso>
                            </CLPerfilNivelAcesso>
                        </NiveisAcesso>
                        <Modulos>
                            <CLPerfilModulo>
                                <Id>19</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>9</Id>
                                    <Nome>Portais</Nome>
                                    <Codigo>256</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                            <CLPerfilModulo>
                                <Id>20</Id>
                                <Perfil>
                                    <Id>12</Id>
                                    <Nome>Sites Externos</Nome>
                                    <Descricao />
                                    <NiveisAcesso />
                                    <Modulos />
                                    <Atividades />
                                </Perfil>
                                <Modulo>
                                    <Id>2</Id>
                                    <Nome>Processos</Nome>
                                    <Codigo>2</Codigo>
                                    <Descricao />
                                </Modulo>
                            </CLPerfilModulo>
                        </Modulos>
                        <Atividades />
                    </Perfil>
                    <Skype />
                    <EmpresaAtual>
                        <Id>0</Id>
                        <SituacaoCache>Inalterado</SituacaoCache>
                        <Nome />
                        <RazaoSocial />
                        <Cnpj />
                        <Endereco />
                        <Bairro />
                        <Cidade />
                        <Estado />
                        <Pais />
                        <Cep />
                        <SistemaWooba>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaWooba>
                        <SistemaSisav>
                            <Id>0</Id>
                            <SituacaoCache>Inalterado</SituacaoCache>
                            <Codigo />
                            <Nome />
                            <Wooba>0</Wooba>
                            <Observacoes />
                            <TemBilhetes>true</TemBilhetes>
                            <PermiteBilheteSemLocalizador>false</PermiteBilheteSemLocalizador>
                            <Campos />
                        </SistemaSisav>
                        <Arquivo>
                            <Nome />
                            <Extensao />
                            <Hash />
                            <Conteudo />
                        </Arquivo>
                    </EmpresaAtual>
                    <DeveAlterarSenha>false</DeveAlterarSenha>
                    <SenhaNuncaExpira>false</SenhaNuncaExpira>
                    <DataAlteracaoSenha>2015-11-10T14:53:45.647</DataAlteracaoSenha>
                    <DataAlteracaoEmail>0001-01-01T00:00:00</DataAlteracaoEmail>
                    <DataAlteracaoCelular>0001-01-01T00:00:00</DataAlteracaoCelular>
                    <Perguntas>0</Perguntas>
                    <UsaBloqueioIP>false</UsaBloqueioIP>
                    <JornadaTrabalho>
                        <Id>0</Id>
                        <Nome />
                        <Prioridade>0</Prioridade>
                    </JornadaTrabalho>
                    <Sexo>Masculino</Sexo>
                    <TokenSSO />
                    <Arquivo>
                        <Nome />
                        <Extensao />
                        <Hash />
                        <Conteudo />
                    </Arquivo>
                </Retorno>
            </LogOnResult>
        </LogOnResponse>
    </soap:Body>
</soap:Envelope>
<pre>

In tests the PHP code below when running shows me the following message XML does not exist

$UrlWSLogin = new SoapClient('https://ws.dominio.com.br/integrador/integrador.asmx?WSDL', array('trace' => 1));
//print_r($UrlWS->__getFunctions());

$MetodoLoginWS = 'LogOn';

$DadosLoginWs = array(
    "Sequencia" => "0",
    "SessionId" => "0",
    "prUsuario" => "login",
    "prSenha" => "senha",
);

$ResultadoWS = $UrlWSLogin->$MetodoLoginWS($DadosLoginWs);

//$RespostaWS = '<pre>'.print_r($ResultadoWS,true).'</pre>';

if (isset($ResultadoWS)) {
    //echo '<pre>'. print_r($UrlWSLogin->__getLastResponse());'</pre>';
    
    $XMLws = $UrlWSLogin->__getLastResponse(); // usando __getLastResponse tenho acesso ao header do soap

    if (!$xml = simplexml_load_string("$XMLws")) {
        echo 'XML não existe';
    } else {
        echo $xml->Sessao->SessionId;
    }
    
    echo "Falha ao capturar xml do ws";
}

Would I have some treatment so I can convert the object tags into variables so I can work with them easier than saving tag data into variables?

    
asked by anonymous 13.11.2015 / 16:36

1 answer

0

Well, come on ...
The truth is that you should not need any parser, XML reader to parse the XML data returned by the query to the web service via SOAP. The SOAPClient itself should be able to do this without extra parsing of the XML tree.

  

All of the examples below are based on the XML of the author's response from   issue.

This should look something like this:

$client = new SoapClient('arquivo WSDL');
$response = $client->LogOn($DadosLoginWs);
print $response->Header->Sessao->Sequencia;
// ...

As far as I know the code above should serve very well. However, if you still want to parse the XML, here's how you should proceed:

DOMDocument / DOMDocument :: DOMXPath ()

# Registre corretamente o domínio namespace
$namespaceDomain = 'http://dominio.com.br';
# Isso na verdade é somente XML em string
$xmldata = file_get_contents('http://localhost/soap.xml');

$dom = DOMDocument::loadXML($xmldata);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('sessao', $namespaceDomain);
#retorna DOMNode (servirá de contexto)
$sessao = $xpath->query('//soap:Header/sessao:Sessao')->item(0); 
$sessaoSeq = $xpath->query('sessao:Sequencia', $sessao)->item(0)->nodeValue;
$sessaoId  = $xpath->query('sessao:SessionId', $sessao)->item(0)->nodeValue;

SimpleXMLElement / SimpleXMLElement :: xpath ()

$reader = new SimpleXMLElement($xmldata);
$reader->registerXPathNamespace('sessao', $namespaceDomain);
$sessao = $reader->xpath('//soap:Header/sessao:Sessao');
$sessaoSeq = $sessao[0]->Sequencia;
$sessaoId  = $sessao[0]->SessionId;

As you can see, it is necessary to register the namespace before analyzing the nodes in the XML tree, otherwise it will not work! This is because, in your case, the Sessao node has a namespace, so to access your descendants you need to inform the prefix namespace. The namespace prefix can be any name.

Useful links:
18.11.2015 / 19:18