Browse Site

php SOAP Service with XML

I was given the task of calling a web service in php recently that formats the parameters as an XML (Extensible Markup Language) document. As I’ve always housed parameters in arrays before for soap calls, and usually utilise XML web services as XML-RPC calls, this was something new to me.

There’s a bit of snobbery out there about XML. I’ve heard plenty of developers, who should know better quite frankly, wax lyrical about how XML is useless and near-to-dead. That’s regardless of what’s been built upon it such as RSS, Atom, SOAP, and XHTML, and how prevailingly these languages are used today. Personally I see XML as a tool like any other; I’m not going to spend hours of my time trying to convince you one way or another but if XML is a possible solution to a problem then I’ll consider using it while it’s at my disposal to do so.

In order to make the SOAP call use XML, we need to build the XML document first. This is easy, using php’s SimpleXMLElement…

$xml = new SimpleXMLElement("<first_element></ first_element >");

This gives you the SimpleXMLElement object with your opening and closing markup tags. You can then begin to flesh out your XML with tiers and data in the following way…

$user_id = $xml->addChild('USER_ID', $user_id);

$first_tier = $xml->addChild('FIRST_TIER', '');

$first_tier ->addChild(‘DETAIL_1’, $detail1);
$first_tier ->addChild(‘DETAIL_2’, $detail2);
$first_tier ->addChild(‘DETAIL_3’, $detail3);

$second_tier = $xml->addChild('SECOND_TIER', '');

$second_tier ->addChild(‘DETAIL_4’, $detail4);
$second_tier ->addChild(‘DETAIL_5’, $detail5);
$second_tier ->addChild(‘DETAIL_6’, $detail6);

This arrangement will give you the following XML output:

</ first_element >

By the way you can echo out the XML to your page via the following code (without echoing out anything else on your page):

Header('Content-type: text/xml');
echo $xml->asXML();

Once your XML is in the correct format, simply make your SOAP call and output your XML into the parameters into the correct argument:

$client = new SoapClient($soap_server_url);

$soap_result = $client->command(array('input' => $xml->asXML()));

Where ‘command’ is the function name on the web service, and ‘input’ is the parameter that you’re naming your XML data.

If the web service’s response is also in XML, you can create a new SimpleXMLElement object from the call:

$xml_output = new SimpleXMLElement($soap_result->command);



This entry was posted in Geeky Stuff, php.

2 Responses to php SOAP Service with XML

  1. Pingback:

  2. Rafaela says:

    Superb tips! I have been hunting for something similar to this for a time now. Appreciate it!