PHP SOAP Web Service With NuSOAP
In this tutorial, we create a SOAP web service in PHP. We use NuSOAP as a third party library for this tutorial. NuSOAP is a very useful library that eases SOAP web service implementation.
It is a set of PHP classes – no PHP extensions required – that allow developers to create and consume web services based on SOAP 1.1, WSDL 1.1 and HTTP 1.0/1.1.
Download NuSOAP
Copy the lib folder to the project.
We use a simple function that performs zip code loookup as our web service.
First we create SOAP server which exposes the functionality for its clients.
zip_code_server.php
configureWSDL("zipcodelist", "urn:zipcodelist");
//Register web service function so that clients can access
$server->register("get_zip_code",
array("area" => "xsd:string"),
array("return" => "xsd:int"),
"urn:zipcodelist",
"urn:zipcodelist#get_zip_code",
"rpc",
"encoded",
"Retrieve zip code for a given area");
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($POST_DATA);
?>
Now, run the server. You will see a link to wsdl file. Click that link and view the generated wsdl file. Clients who access the web service needs this wsdl. Save this file with .wsdl extension. You need to specify the URL for wsdl file within client.
zip_code_client.php
getError();
if ($error) {
echo "
Constructor error
" . $error . "";
}
//Use basic authentication method
$client->setCredentials("codezone4", "123", "basic");
$result = "";
if ($client) {
$result = $client->call("get_zip_code", array("area" => "Cheltenham"));
}
if ($client->fault) {
echo "
Fault
"; print_r($result); echo "";
} else {
$error = $client->getError();
if ($error) {
echo "
Error
" . $error . "";
} else {
echo "
zip code
"; echo $result; echo "";
}
}
echo "
Request
";echo "
" . htmlspecialchars($client->request, ENT_QUOTES) . "";
echo "
Response
";echo "
" . htmlspecialchars($client->response, ENT_QUOTES) . ""
?>