PHP SOAP Messages with Attachments
Aug 9th, 2009 by paolo
This article is to make a simple example on how you can manage SOAP Messages with Attachements in PHP and, in particular, I'll describe how to use the PEAR::SOAP package to transmit files associated to a SOAP message as attachments in their native format in a multipart MIME structure for transport (SOAP Messages with Attachments specifications).
Even if the PEAR::SOAP package is not yet considered stable and even if it lacks completely of documentation, the use of it is the only way I found to solve this problem. Nor the standard SOAP PHP5 implementation, nor the Zend_Soap package in the Zend Framework provides any way to manage attachments to SOAP messages.
The first problem you have with PEAR::SOAP is the lack of documentation, no API documentation, no examples, nothing except what you can find within the source code. So, if you want to use it in the proper way, you have to read and understand the source code and make many many tests.
The example I'll make will invoke an operation that requires a binary file as first parameter. First we have to create a SOAP client using the wsdl of the webservice to invoke. Assuming you have correctly installed the PEAR:SOAP package, the code to create a client is very simple.
-
require "SOAP/Client.php";
-
-
$wsdl = new SOAP_WSDL('http://somehost.com/webservice.wsdl');
-
$client = $wsdl->getProxy();
Once you have a client for the webservice to invoke it's time to set some options, for example if the target webservice needs an HTTP authentication you have to set user and pass options.
-
$client->setOpt('user', 'myusername');
-
$client->setOpt('pass', 'mypassword');
Now we assume to have a webservice with a register operation that takes only one parameter and this parameter is an xml file. If the xml file has to be transferrered as an attachment we have first to build a SOAP_Attachment object, then we have to chose the method used by the framework to transport the binary content and finally we have to invoke the register operation passing the created attachment as parameter.
-
$v = new SOAP_Attachment('contentID', 'text/xml; charset=utf-8', null, $xml);
-
$client->setOpt('Mime', true);
-
$ret = $client->register($v);
If you don't have the binary file already loaded in a string, but you have a file on your filesystem, the first line of the last code snippet has to be modified as follows:
-
$v = new SOAP_Attachment('contentID', 'text/xml; charset=utf-8', 'filename.xml');

