phpxmlsoapsimplexml

SOAP XML inside XML - How to parse with PHP


I've searched in the SO, but nothing what I've found could help me.

I'm doing system integration with JadLog, a freight service.

When I pass the query with the product and delivery variables, an XML is returned.

Return example:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<valorarResponse xmlns="">
<ns1:valorarReturn xmlns:ns1="http://jadlogEdiws">
<?xml version="1.0" encoding="utf-8" ?> 
<string xmlns="http://www.jadlog.com.br/JadlogEdiWs/services"> 
   <Jadlog_Valor_Frete> 
       <versao>1.0</versao> 
       <Retorno>1458,62</Retorno> 
       <Mensagem>Valor do Frete</Mensagem> 
   </Jadlog_Valor_Frete> 
</string>
</ns1:valorarReturn>
</valorarResponse>
</soapenv:Body>
</soapenv:Envelope>

So, there is more than one XML declaration, right?

The only value that I need is the value of the freight, which is in the tag Retorno. I this case, 1458,62.

What am I trying to do:

$your_xml_response = file_get_contents($url_project);

$clean_xml = str_replace('soapenv:', '', $your_xml_response);

$xml = simplexml_load_string($clean_xml);

var_dump($xml);

What its returns:

object(SimpleXMLElement)[1]
  public 'Body' => 
    object(SimpleXMLElement)[2]
      public 'valorarResponse' => 
        object(SimpleXMLElement)[3]

If I try to echo $xml->Retorno, it Returns empty.

How can I get the value of tag Retorno?


Solution

  • When I tried to load your XML string with simplexml_load_string it causes me There is more than one XML declaration which is not allowed in xml . That's why I used regular express to get Retorno value. May be its not the best approach to use regex on XML but you can make a try.

    <?php
    $re = '/<Retorno>(.*?)<\/Retorno>/m';
    $str = '<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
    <valorarResponse xmlns="">
    <ns1:valorarReturn xmlns:ns1="http://jadlogEdiws">
    <?xml version="1.0" encoding="utf-8" ?> 
    <string xmlns="http://www.jadlog.com.br/JadlogEdiWs/services"> 
       <Jadlog_Valor_Frete> 
           <versao>1.0</versao> 
           <Retorno>1458,62</Retorno> 
           <Mensagem>Valor do Frete</Mensagem> 
       </Jadlog_Valor_Frete> 
    </string>
    </ns1:valorarReturn>
    </valorarResponse>
    </soapenv:Body>
    </soapenv:Envelope>
    ';
    
    preg_match_all($re, $str, $matches);
    
    //debugging
    print '<pre>';
    print_r($matches);
    print '<pre>';
    //result
    echo $matches[0][0];