Creating Web Services with PHP and SOAP – Part 1

Building a SOAP Server

It couldn’t be easier to get NuSOAP up and running on your server; just visit sourceforge.net/projects/nusoap, download and unzip the package in your web root direoctry, and you’re done. To use the library just include the nusoap.php file in your code.

For the server, let’s say we’ve been given the task of building a service to provide a listing of products given a product category. The server should read in the category from a request, look up any products that match the category, and return the list to the user in a CSV format.

Create a file in your web root named productlist.php with the following code:


<?php


<?php
require_once('lib/nusoap.php');

function getProd($category) {
 if ($category == "books") {
 return join(",", array(
 "The WordPress Anthology",
 "PHP Master: Write Cutting Edge Code",
 "Build Your Own Website the Right Way"));
 }
 else {
 return "No products listed under that category";
 }
}

$server = new soap_server();
$server->register("getProd");
$server->service($HTTP_RAW_POST_DATA);

?>

Building a SOAP Client

Then create productlistclient.php as follows


<?php
require_once('lib/nusoap.php');
$client = new nusoap_client("http://localhost/webservice/productlist.php");

$error = $client->getError();
if ($error) {
 echo "<h2>Constructor error</h2><pre>" . $error . "</pre>";
}

$result = $client->call("getProd", array("category" => "books"));

if ($client->fault) {
 echo "<h2>Fault</h2><pre>";
 print_r($result);
 echo "</pre>";
}
else {
 $error = $client->getError();
 if ($error) {
 echo "<h2>Error</h2><pre>" . $error . "</pre>";
 }
 else {
 echo "<h2>Books</h2><pre>";
 echo $result;
 echo "</pre>";
 }
}
?>

Now go to http://localhost/webservice/productlistclient.php

Advertisements

One thought on “Creating Web Services with PHP and SOAP – Part 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s