Home >Backend Development >PHP Tutorial >How to Efficiently Parse SOAP XML with Namespace Prefixes Using SimpleXML?
How to Parse SOAP XML: Stripping Namespace Prefixes for SimpleXML
When parsing SOAP XML documents, namespace prefixes can present challenges for libraries like simplexml. This issue arises when encountering XML responses similar to the following:
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <PaymentNotification xmlns="http://apilistener.envoyservices.com"> <payment> <!-- Payment data --> </payment> </PaymentNotification> </soap:Body> </soap:Envelope>
Attempts to parse such an XML string using simplexml, such as the following code, often result in empty results:
$xml = simplexml_load_string($soap_response); $xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/'); foreach ($xml->xpath('//payment') as $item) { print_r($item); }
To resolve this issue and successfully parse SOAP XML with namespace prefixes, a simple yet effective approach is to strip these prefixes before passing the XML to simplexml. Here's how it's done:
$your_xml_response = '<Your XML here>'; $clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $your_xml_response); $xml = simplexml_load_string($clean_xml);
By removing the namespace prefixes, the XML becomes easier for simplexml to parse. The resulting SimpleXMLElement object would contain the desired data nested under
The above is the detailed content of How to Efficiently Parse SOAP XML with Namespace Prefixes Using SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!