Parsing SOAP responses with PHP’s SimpleXML

We recently discussed parsing XML with SimpleXML and since that writing I ran into a situation where I needed to parse a SOAP response. As it turns out, SOAP responses are a totally different beast when it comes to parsing them with SimpleXML. SOAP responses contain namespaces on some if not all of the nodes and SimpleXML doesn’t really care for that when using the traditional method of interaction. To accomplish this, you will need to use the SimpleXMLElement::children() method to specify the namespace:

// Mocks our SOAP response
$soap_response = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="" xmlns:ns1="">
				<ns1:Title>Parsing SOAP responses with SimpleXML</ns1:Title>
				<ns1:Description>Awesome post about parsing SOAP responses.</ns1:Description>
					<ns1:Name>Josh Sherman</ns1:Name>
				<ns1:Title>How to parse XML with SimpleXML</ns1:Title>
				<ns1:Description>Awesome post about parsing XML.</ns1:Description>
					<ns1:Name>Josh Sherman</ns1:Name>

// Loads the XML
$xml = simplexml_load_string($soap_response);

// Grabs the posts
$posts = $xml->children('SOAP-ENV', true)->Body->children('ns1', true)->Posts->Post;

// Take the posts and generate some markup
foreach ($posts as $post)
	$twitter_url = '' . $post->Author->Twitter;

	echo '
			<h1>' . $post->Title . '</h1>
			<time>' . $post->PostedDate . '</time>
			<a href="' . $twitter_url . ' rel="author">' . $post->Author->Name . '</a>
			<p>' . $post->Description . '</p>
			<a href="' . $post->Link . '">Read Article</a>

Simply calling $xml->SOAP-ENV:Envelope will result in an error due to the fact that hyphens and colons are not valid characters for object variables or methods. Whenever you are entering a new namespace, you can use SimpleXMLElement::children() to define the name space. The second argument tells the method that you are defining a prefix and not a namespace URL.

Please note that the SimpleXMLElement::children() method will always return a SimpleXMLElement whether the node has any children or not.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.