PHP and Web Service

I will be discussing a very simple example of using web services with PHP. The Web Service consumes a zip code (US zip code in our example) and returns an array containing the City, State, Area Code and Time Zone. To keep things simple, I will only convert Zip Code into City and State.
Web Service used: http://www.webservicex.net/uszip.asmx?op=GetInfoByZIP
Web Service WSDL: http://www.webservicex.net/uszip.asmx?WSDL
Programming Language: PHP
Framework: WordPress. Valid for any framework using PHP.
PHP APIs: SOAP Client, XML Parser
The code follows:
$zipcode = $_POST['zipcode']; //I am fetching the zip code via an ajax call from an user input
$url = "http://www.webservicex.net/uszip.asmx?WSDL";
$client = new SoapClient($url); //create a new SOAP client object and feed it with the WSDL URL
//$fns = $client->__getFunctions(); //You can dump the available functions using the getFunctions method
//var_dump($fns); //dumping the functions reveal the method definitions
$res = $client->GetInfoByZIP(array('USZip' => $zipcode)); //use the GetInfoByZIP method passing the USZip as an array parameter
$parsedXML = simplexml_load_string($res->GetInfoByZIPResult->any); //the returned value is in XML format which can be easily parsed using PHP XML parser
$city = $parsedXML->Table[0]->CITY; //fetch the city
$state = $parsedXML->Table[0]->STATE; //fetch the state

The output of the line var_dump($fns) is attached below.Method dump
As you can see, the GetInfoByZIP method has an array parameter and returns a complex type GetInfoByZIPResponse. The same can be verified from the WSDL mentioned in this post. This example can be used with any kind of web service and scaled as per business requirements.
Hope this helps! Please leave your valuable comments and let me know what you think.

Leave a comment