PHP Web Services Tutorial: We ever talk about web services at here. In this post, we talk about how to create data array in server. Client will send two data: name and birthday. In the same time, client will fetch array ( name and age). It is realy simple.
I modify from our practice about web services. Create "server_array.php". Placed within (example) www/test/nusoap. Enter this codes:
<?
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('hello');
// create age calculation function
function find_age($birthday)
{
list($byear, $bmonth, $bday) = explode('-', $birthday);
list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
$cday -= $bday;
$cmonth -= $bmonth;
$cyear -= $byear;
if($cday < 0)
$cmonth--;
if($cmonth < 0)
$cyear--;
return $cyear;
}
// create the function
function hello($name,$birthday)
{
if(!$name){
return new soap_fault('Client','','Put your name!');
}
$result = array('name'=>$name,'age'=>find_age($birthday));
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
Now, this is client side. Create "client_side.php". Put within www/test/nusoap. Enter following codes:
<?
require_once ('lib/nusoap.php');
$param = array( 'name' => 'Babablackship','birthday'=>'1980-12-24');
$client = new soapclient('http://localhost:8048/test/nusoap/server_array.php');
$response = $client->call('hello',$param);
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode.")</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response['name'];
echo "<br>";
echo "Age: ".$response['age']."'s";
}
?>
Ok. Now, point your browser to http://localhost/nusoap/test/client_array.php. You must see like this: