Wash, rinse, repeat – SOAP Bodies and calls in PHP

As part of the current job, I’ve been looking closely at SOAP and getting PHP to connect to endpoints written in other languages by other people.

In my last job, I used SOAP to set up services to be contacted by  external suppliers and created the server. One of the challenges that I faced in a recent project was to connect to a remote endpoint to which I have no access.

The process has been successful but the coding made me look at the process of creating the XML message. I realised that there are two ways of doing it with slightly different effects.

After creating the SOAP client with $client = new SOAPClient(‘<pathto.wsdl>’); the PHP manual suggests that you use

$client->__soapCall(‘<functionname’, array(‘key’=>’value’));

which replaces $client->__call(); (now deprecated).

This function allows you to replace the contents of the Xml in the soap body. For example, if the receiving method requires string $name, string $message, then you can use

$client->__soapCall(‘functionname’, array(‘name=>’person, ‘message’=>’hello’));

This should create the Xml body of

<ns1:functionname><name>person</name><message>hello</message></functionname>

which the function name on the server will accept.

It might also be the case though that you just need to send some pre-defined Xml string (such as an Origo message used in insurance in the UK). In that case, there is another way of sending the data across to functionname(string $xmlmessage). Rather than using

$client->__call(‘functionname’, array());

you can use $client->functionname(string $xml); which will send the defined Xml to the server.

One that you need to watch is that the receiving function is expecting the Xml or the plain string. It cannot deal with many values but is useful for sending a defined Xml structure across services.

It may not be ground breaking news but that minor diversion did give me a better insight into the internals of SOAP functions and how to best define the body.