Saturday, January 21, 2012

Web Services in PHP

In this Post, we shall create a Web Service in PHP, and call it through a PHP Client.


The following steps are required before we begin :-

1) Download the file php_soap.dll and copy it into the PHP directory.
Next , make the following entry in the PHP.ini file

In this Web Service we shall create a single function called sayHello

Here is the code for this function :-
function sayHello($name)
{
return "Hello $name";
}


Next create a WSDL file for this function:-

sayhello.wsdl

<?xml version="1.0" ?>
<definitions name="welcome"
targetNamespace="http://localhost:777/HypatiaWebServices/sayHello"
xmlns:tns="http://localhost:777/HypatiaWebServices/sayHello"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
  <message name="sayHelloRequest">
    <part name="name" type="xsd:string" />
  </message>
  <message name="sayHelloResponse">
    <part name="return" type="xsd:string" />
  </message>
  <portType name="QuotePortType">
    <operation name="sayHello">
      <input message="tns:sayHelloRequest" />
      <output message="tns:sayHelloResponse" />
    </operation>
  </portType>
  <binding name="QuoteBinding" type="tns:QuotePortType">
    <soap:binding
    style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
    <operation name="sayHello">
      <soap:operation soapAction="" />
      <input>
        <soap:body use="encoded"
        encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
        <soap:body use="encoded"
        encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
    </operation>
  </binding>
  <service name="welcome">
    <documentation>Says Hello to you</documentation>
    <port name="QuotePort" binding="tns:QuoteBinding">
      <soap:address
      location="http://localhost:777/HypatiaWebServices/HypatiaWebServiceServer.php" />
    </port>
  </service>
</definitions>


Next create the Web Service Server

Here is the code for the server:-


HypatiaWebServiceServer.php
<?php
function sayHello($name)
{
return "Hello $name";
}
$server=new SoapServer("sayhello.wsdl");
$server->addFunction("sayHello");
$server->handle();
?>

Here is the WSDL file as viewed in a Browser:-





Next create a PHP Client. Here we provide the URL to the WSDL.Then simply call the function.The parameters are passed in an array. Here is the complete code:-


HypatiaWebServiceClient.php

<?php
$client=new SoapClient("http://localhost:777/HypatiaWebServices/HypatiaWebServiceServer.php?wsdl");
print $client->__call("sayHello",(array("Champak")));
?>

Here is the output in firefox:-



No comments:

Post a Comment