Omnichannel Services – Call a SOAP Service

Today I’m going to show you how to consume a SOAP web service with PHP and transform its content to JSON, so that it’s easily consumable by apps and webs.

Many web services are provided according to the SOAP standard, whether they are publicly available on the Internet or internal services provided by the back-end systems. SOAP is based on XML, and SOAP even adds more metadata to the already verbose XML format. Therefore, we have a lot to win in terms of bandwidth and performance by transforming the information to the much more efficient JSON format. As with most omnichannel service, this way we can also make sure that only the information that is needed is transferred.

This time the example is a public SOAP web service provided by the Swedish Central Bank, and it allows us to query for exchange rates related to Swedish currency (kronor). The idea is that an app could allow the user to select a year and a month, and then show a list of the average exchange rates for that month. Even if this is a simple example, there is not much difference with getting information from a back-end system like SAP, Siebel or PeopleSoft. In a real-world scenario, the work of the service would be divided into different tiers with specific responsibility (low-end services to connect to back-ends, high-end services to add business logic and processes, and front-end services that provide customized functionality and data to the touch points, i.e. apps and webs).

Let’s start by looking at how we request the web service with SOAP. This is the body of the HTTP request, and as you can see it’s in XML format and that SOAP is adding a significant overhead of metadata to send the three parameters. This is what we get back from the web service, and just as in the request, there is a lot of metadata and overhead to the two pieces of information we want to send to the app, which is what you see here – a very slim array of currency codes and average exchange rates, in JSON format.

In the PHP code we first get the parameters (line 2-3). Then we create the SOAP client (line 4), and call it with the parameters (line 5). The result is the XML in the tag (getMonthlyAverageExchangeRatesResponse) inside the Body tag of the SOAP response. For each found exchange rate (series, on line 7), the currency code and average is parsed (line 10-11), and added to an array (line 12). Then a root object (line 14) and headers (line 15-16) are added to the response before it’s converted to JSON and returned to the app (line 17).

To put this code on your server, please see the end of my previous video, http://youtu.be/P9PaOq587g0?t=4m43s, and then it can be called with (replace 0.0.0.0 with the IP address of your server):

http://0.0.0.0/getExchangeRates?year=2014&month=2

There you have an omnichannel service that calls a SOAP web service and transform the data to JSON that can be easily consumed by your apps or webs.

You can download the source code.