How to use Soap Service in PHP with curl

By Shekhar Gigras

Initialize variables

$soapUrl =

$soapUser = if required

$soapPassword = if requiref

Create Request string

$xml_post_string = '
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:sap-com:document:sap:rfc:functions"> 
<soapenv:header> 
<soapenv:body> 
<root> 
<child> 
<empid>7</empid> 
</child> 
</root> 
</soapenv:body> 
</soapenv:header>
</soapenv:envelope>'; 

Set Http Header for Curl

$headers = array( 
"Content-type: text/xml;charset=\"utf-8\"", 
"Accept: text/xml", 
"Cache-Control: no-cache", 
"Pragma: no-cache", 
"Content-length: ".strlen($xml_post_string), ); 
//SOAPAction: your op URL 

Initialize Curl

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); 
curl_setopt($ch, CURLOPT_URL, $soapUrl); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch); curl_close($ch); 

Reponse string like this

<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> 
<soap-env:header> 
<soap-env:body> 
<n0:rootresponse xmlns:n0="urn:sap-com:document:sap:rfc:functions"> 
<manager> 
<empid>00000007</empid> 
</manager> 
</n0:rootresponse> 
</soap-env:body> 
</soap-env:header>
</soap-env:envelope> 

How to read this xml, we can't read this xml directly because namespace("urn:sap-com:document:sap:rfc:functions") is exists in response.

$soap = simplexml_load_string($response); 
$soap->registerXPathNamespace('ns1', 'urn:sap-com:document:sap:rfc:functions'); 
$productsResult = $soap->xpath('//ns1:RootResponse')[0]; 
$objArray= xml2array($productsResult); 
$obj = $objArray["Manager"]; 
print_r("Employee ID : " .$obj["empid"]); 

function xml2array ($xmlObject) 
{ 
$objArray = array(); 
foreach ( (array) $xmlObject as $index => $node ) 
$objArray[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node; return $objArray; 
} 

Connect by Whatsapp

Posted in PHP on May 23, 2020


Comments

Please sign in to comment!