PHP SOAP example

In order to deploy a webservice API you need at least a server and a client. PHP Soap makes the day!

First install php-soap. Let’s suppose to be on a CentOS distro, you should issue a:

yum install php-soap

remember to reload Apache as well, with a

service httpd restart

Now you are ready to create two files. For sake of simplicity we will call them server.php and client.php.

Let’s see how the server.php is made:

<?php

// server
class MySoapServer
{
  public function getMessage()
  {
    return 'Hello, World!';
  }

  public function addNumbers($num1,$num2)
  {
    return $num1 + $num2;
  }

  public function multNumbers($num1,$num2)
  {
    return $num1 * $num2;
  }
}

$options= array('uri'=>'http://192.168.116.128/playground/test/');

$server=new SoapServer(NULL,$options);
$server->setClass('MySoapServer');
$server->handle();

?>

as you can easily understand the API exposes three methods: getMessage(), addNumbers(), multNumbers().

And now the client.php:

<?php

// client

$options= array(
  'location'    =>  'http://192.168.116.128/playground/test/server.php',
  'uri'     =>  'http://192.168.116.128/playground/test/server.php'
);

$client=new SoapClient(NULL,$options);
echo $client->getMessage();  //Hello,World!
echo $client->multNumbers(23,3); //  69

?>

That’s all folks.