How to modify a SoapClient request in PHP

By | January 13, 2023


SOAP is a protocol to exchange objects over http. It is used to implement apis and the data being exchanged is in xml format. Sometimes it might be required to modify the soap request to add custom http headers for example. Since SoapClient is a class, it can be extended and the request process can be modified.

Here is a quick example


class SoapClientDebug extends SoapClient
	public function __doRequest($request, $location, $action, $version, $one_way = NULL) 
		$soap_request = $request;
		$header = array(
			"Content-type: text/xml;charset="utf-8"",
			/*"Accept: text/xml",*/
			"Cache-Control: no-cache",
			"Pragma: no-cache",
			"SOAPAction: "$action"",
			"Content-length: ".strlen($soap_request),
		$soap_do = curl_init();
		$url = $location;
		$options = array( 
			//CURLOPT_HEADER         => true,
			CURLOPT_USERAGENT      => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
			//CURLOPT_VERBOSE        => true,
			CURLOPT_URL            => $url ,
			CURLOPT_POSTFIELDS => $soap_request ,
			CURLOPT_HTTPHEADER => $header ,
		curl_setopt_array($soap_do , $options);
		$output = curl_exec($soap_do);
		if( $output === false) 
			$err = 'Curl error: ' . curl_error($soap_do);
			print $err;
			///Operation completed successfully
		// Uncomment the following line, if you actually want to do the request
		// return parent::__doRequest($request, $location, $action, $version);
		return $output;

The __doRequest method of the SoapClient class is over-ridden and the request is reconstructed using CURL. The $request variable that is passed to the method has the xml of the request constructed according to the wsdl.

Now the SoapClientDebug class can be used in place of SoapClient class throughout the code.

$client = new SoapClientDebug( 'api.wsdl' , $opts);


The entire soap request can be saved to a file for example. Just save the contents of $request variable to some file in the __doRequest function. The following example shows how to save the request xml to a file with minimum code.

class SoapClientDebug extends SoapClient
	public function __doRequest($request, $location, $action, $version, $one_way = NULL) 
		file_put_contents('soap_log.txt', $request);
		return parent::__doRequest($request, $location, $action, $version);

It simply calls the parent version of the __doRequest function to do the task.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].


How to modify a SoapClient request in PHP
  1. Stephen Blackstone

    Two small issues in this code, in the header lines that include a double-quote, you’ll need to escape them.

Leave a Reply

Your email address will not be published. Required fields are marked *