Monday, August 24, 2015

PHP Parse SOAP XML Response

Recently in one of my project we were using SOAP service which was having XML response that we have to parse with PHP. For some reason PHP SOAP client was giving some because it XML response was using name namespaces and that was not parsed correctly with SOAP client. Here in this blog I am going to explain how to call XML web service without using SOAP client and parse response with PHP.

We will use PHP cURL. First lets create XML post data.

$postString = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi=""                 xmlns:xsd="" xmlns:soap="">
<GetProducts xmlns="">

So that's our post data. Now lets create cURL request.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: text/xml; charset=utf-8',
                                            'Connection: Keep-Alive',
$result = curl_exec($ch);

Now you will get XML response in $result which is in string format. We will use SimpleXML class of PHP.

$soap = simplexml_load_string($result);

That will load SimpleXML object. Now we will register namespace.

$soap->registerXPathNamespace('ns1', '');

Now you can use XPATH to go to specific nodes.

$productsResult = $soap->xpath('//ns1:GetProductsResponse/ns1:GetProductsResult')[0]->Products;

$product = $productsResult->Product[$i];
echo "Product ".$i;
echo "Name : ".$product->Name;
echo "SCRef : ".$product->SCRef;
echo "Description : ".$product->Description;
echo "PriceRange : ".$product->PriceRange;
echo "ProductType : ".$product->ProductType;
echo "ProductGroups : ".$product->ProductGroups;
echo "Colours : ".$product->Colours;
echo "ThumbImageURL : ".$product->ThumbImageURL;
echo "LargeImageURL : ".$product->LargeImageURL;

That's it. In the same way you can parse any other XML response.