Creating Web Services with PHP and SOAP

There are two basic approaches that are used to create web services from scratch. In this first of a two part series on web services I’ll talk about the 'top-down' approach. According with this approach, we need to produce the XML description of the service before it is implemented. So the service is fully described in terms of what it does, how it can be called and what result(s) it returns, but is not actually implemented. This (WSDL) specification is then used as a guide to writing the code that implements the service.

The project structure

The webservice will receive a string parameter and it will return the 'hello' string concatenated with the input parameter. For example, if the input is 'Andrea', then the output will be 'Hello Andrea'. In order to achieve this, we need to define the WSDL descriptor.

The descriptor.wsdl
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions name="HelloWS"

 <wsdl:message name="helloRequest">
  <wsdl:part name="name" type="xsd:string"></wsdl:part>
 <wsdl:message name="helloResponse">
  <wsdl:part name="result" type="xsd:string"></wsdl:part>
 <wsdl:portType name="HelloWS">
  <wsdl:operation name="hello">
            <wsdl:input message="tns:helloRequest"/>
            <wsdl:output message="tns:helloResponse"/>
 <wsdl:binding name="HelloWSPortBinding" type="tns:HelloWS">
  <soap:binding style="rpc" transport=""/>
  <wsdl:operation name="hello">
   <soap:operation soapAction="http://localhost/soap_demo/server.php"/>
    <soap:body use="literal"/>
    <soap:body use="literal"/>
 <wsdl:service name="HelloWS">
  <wsdl:port name="HelloWSPort" binding="tns:HelloWSPortBinding">
   <soap:address location="http://localhost/soap_demo/server.php"/>
We also need to implement the hello method in a php file.

The server.php file
// turn off WSDL caching

function hello($name)
 return 'Hello '.' '.$name;

// initialize SOAP Server
$server = new SoapServer("descriptor.wsdl",[]);
// register available functions
// start handling requests
Now, we can import the WSDL file into SoapUI for example and the results should look like this:

The SOAP request.
<soapenv:Envelope xmlns:soapenv="" xmlns:ws="">
The SOAP response.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="">
         <result>Hello  Andrea</result>
Do not forget to enable the SOAP extension in the php.ini file. To do this, you have to find extension=php_soap.dll in php.ini, remove the semicolon(;) and restart the server.