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:
[sourcecode language=”php”]
<?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);
?>
[/sourcecode]
Building a SOAP Client
Then create productlistclient.php as follows
[sourcecode language=”php”]
<?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>”;
}
}
?>
[/sourcecode]