phpxmlsimplexml

Difficulties in extracting content from a SimpleXMLElement


I have this XML:

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <soapenv:Fault>
      <faultcode>soapenv:Server</faultcode>
      <faultstring>For input string: ""</faultstring>
      <detail />
    </soapenv:Fault>
  </soapenv:Body>
</soapenv:Envelope>

I want to get the content of Body > Fault > faultcode, faultstring

But I'm not getting the expected output with this code:

$xml = "\<?xml version='1.0' encoding='UTF-8'?\>\<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'\>\<soapenv:Body\>\<soapenv:Fault\>\<faultcode\>soapenv:Server\</faultcode\>\<faultstring\>For input string: '\</faultstring\>\<detail /\>\</soapenv:Fault\>\</soapenv:Body\>\</soapenv:Envelope\>";

$xmlObject = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$namespaces = $xmlObject->getNamespaces(true);
$body = $xmlObject->children($namespaces['soapenv'])->Body->Fault->faultcode;
dd($body);

output :

SimpleXMLElement {#1890}

Solution

  • I think your mistake is how you get the "faultstring" property. Remember that you are setting the "soapenv" namespace and the "faultcode" property does not have this namespace. This is the example I was trying:

    <?php
    
    $xml = <<<XML
    <?xml version='1.0' encoding='UTF-8'?>
        <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
            <soapenv:Body>
                <soapenv:Fault>
                    <faultcode>soapenv:Server</faultcode>
                    <faultstring>For input string</faultstring>
                    <detail />
                </soapenv:Fault>
            </soapenv:Body>
        </soapenv:Envelope>
    XML;
    
    $xmlObject = simplexml_load_string($xml);
    $namespaces = $xmlObject->getNamespaces(true);
    $body = $xmlObject->children($namespaces['soapenv'])->Body->Fault;
    
    print_r($body->xpath('faultstring'));
    

    This is the result: Screenshot of result

    I also leave you an example of how I think it would be easier to obtain the value you need from the "faultstring" property:

    <?php
    
    try {
        $dom = new DOMDocument();
        $dom->loadXML($xml);
        $xpath = new DOMXPath($dom);
    
        // Execute XPath query to get "faultstring" property value
        $faultString = $xpath->evaluate('//soapenv:Fault/faultstring');
    
        var_dump($faultString->item(0)->nodeValue);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
    

    This is the result: Screenshot of result