Friday, 14 December 2012

PHP - Web Services: Serving Data Array

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:
01    <?
02     //call library
03     require_once ('lib/nusoap.php');
04   
05     //using soap_server to create server object
06     $server = new soap_server;
07   
08     //register a function that works on server
09     $server->register('hello');
10   
11     // create age calculation function
12     function find_age($birthday)
13     {
14          list($byear, $bmonth, $bday) = explode('-', $birthday);
15          list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
16        
17          $cday -= $bday;
18          $cmonth -= $bmonth;
19          $cyear -= $byear;
20        
21          if($cday < 0)
22          $cmonth--;
23          if($cmonth < 0)
24          $cyear--;
25        
26          return $cyear;
27     }
28   
29     // create the function
30     function hello($name,$birthday)
31     {
32   
33          if(!$name){
34                return new soap_fault('Client','','Put your name!');
35          }
36   
37      <b> $result = array('name'=>$name,'age'=>find_age($birthday));</b>
38          return $result;
39   
40     }
41   
42     // create HTTP listener
43     $server->service($HTTP_RAW_POST_DATA);
44     
45     exit();
46     
47     ?>

Now, this is client side. Create "client_side.php". Put within www/test/nusoap. Enter following codes:
01    <?
02    require_once ('lib/nusoap.php');
03   
04    $param = array( 'name' => 'Babablackship','birthday'=>'1980-12-24');
05   
06    $client = new soapclient('http://localhost:8048/test/nusoap/server_array.php');
07   
08    $response = $client->call('hello',$param);
09   
10    if($client->fault)
11    {
12        echo "FAULT: <p>Code: (".$client->faultcode.")</p>";
13        echo "String: ".$client->faultstring;
14    }
15    else
16    {
17        echo $response['name'];
18        echo "<br>";
19        echo "Age: ".$response['age']."'s";
20    }
21    ?>

Ok. Now, point your browser to http://localhost/nusoap/test/client_array.php. You must see like this:

No comments:

Post a Comment