Posts Tagged soap

Build complex SOAP requests and headers in PHP

When you’re writing PHP code for a company, you’ll need someday to write code that interact with a SOAP webservice. An exemple could be the Paypal SOAP API for ExpressCheckout. The original PHP API is terrible because of his handling of SOAP headers that doesn’t give the control we could want on an item.

The solution to this is to extend the original SoapClient using PHP:

class SoapClientPaypal extends SoapClient
{
    public function __doRequest($request, $location,
                                $action, $version)
    {
        /* the $request element here contain the XML formatted request */
        $dom = new DOMDocument();
        $dom->loadXML($request);

        /* now that you've loaded the request, you can easily add elements,
         * replace them, etc...*/


        /* save the modified request for __getLastRequest() */
        $this->__last_request = $dom->saveXML();
        /* then call the parent function to do the query */
        $response = parent::__doRequest($this->__last_request,
                                        $location, $action, $version);

        /* $response contain the XML response returned by the webservice,
         * you can also change it if needed, for exemple, in paypal I had to
         * replace each occurences of the ebl:GetExpress...DetailsType
         * by xsd:array because PHP would do some really weird things with
         * it ( like referencing the parent, preventing access to child nodes )
         * I do not store the response in __last_response because I want
         * what was returned by the server, not what I changed :D */


        return $response;
    }
}

By doing that, you have a great deal of control on the request/responses coming from a SOAP webservices, the $location var contain the WS URL, the $action is the action called and $version is the SOAP version.

, , , ,

No Comments