Parse XML with Multiple Namespaces Using SimpleXML
Parsing XML documents with multiple namespaces poses a challenge when using SimpleXML. To successfully parse such documents, we must handle the namespace declarations.
The provided XML document has multiple namespaces:
<code class="xml"><soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> <soap-env:Header> <eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader"> ... </eb:MessageHeader> <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext"> ... </wsse:Security> </soap-env:Header> <soap-env:Body> <SessionCreateRS xmlns="http://www.opentravel.org/OTA/2002/11"> ... </SessionCreateRS> </soap-env:Body> </soap-env:Envelope></code>
To parse this document with SimpleXML, we can follow these steps:
<code class="php">$xml = simplexml_load_string($xmlString);</code>
<code class="php">$xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/'); $xml->registerXPathNamespace('eb', 'http://www.ebxml.org/namespaces/messageHeader'); $xml->registerXPathNamespace('wsse', 'http://schemas.xmlsoap.org/ws/2002/12/secext');</code>
<code class="php">foreach ($xml->xpath('//eb:MessageHeader') as $header) { var_dump($header->xpath('//eb:CPAId')); // Outputs "something" }</code>
By following these steps, we can successfully parse XML documents with multiple namespaces using SimpleXML, allowing us to access and manipulate elements within each namespace effectively.
The above is the detailed content of How to Parse XML with Multiple Namespaces Using SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!