Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Web service - SOAP Server/Client in PHP

Simple Web service - SOAP Server/Client in PHP

Implementation of the SOAP server - server.php:

// turn off WSDL caching

// model, which uses in web service functions as parameter
class Book
	public $name;
	public $year;

 * Determines published year of the book by name.
 * @param Book $book book instance with name set.
 * @return int published year of the book or 0 if not found.
function bookYear($book)
	// list of the books
		['name'=>'test 1','year'=>2011],
		['name'=>'test 2','year'=>2012],
		['name'=>'test 3','year'=>2013],
	// search book by name
	foreach($_books as $bk)
			return $bk['year']; // book found

	return 0; // book not found

// initialize SOAP Server
$server=new SoapServer("test.wsdl",[
		'book'=>'Book', // 'book' complex type in WSDL file mapped to the Book PHP class

// register available functions

// start handling requests

Implementation of the SOAP client - client.php:

// model
class Book
	public $name;
	public $year;

// create instance and set a book name
$book      =new Book();
$book->name='test 2';

// initialize SOAP client and call web service function
$client=new SoapClient('',['trace'=>1,'cache_wsdl'=>WSDL_CACHE_NONE]);
$resp  =$client->bookYear($book);

// dump response

Dump of the response:

string '2012' (length=4)

WSDL file test.wsdl:

<?xml version="1.0" encoding="UTF-8"?>

<wsdl:definitions name="Library"


        <xsd:schema xmlns:xsd="" targetNamespace="Library">
            <xsd:complexType name="book">
                    <xsd:element name="name" type="xsd:string"></xsd:element>
                    <xsd:element name="year" type="tns:integer"></xsd:element>

    <wsdl:message name="bookYearRequest">
        <wsdl:part name="book" type="xsd:book"></wsdl:part>
    <wsdl:message name="bookYearResponse">
        <wsdl:part name="year" type="tns:integer"></wsdl:part>

    <wsdl:portType name="Library">
        <wsdl:operation name="bookYear">
            <wsdl:input message="tns:bookYearRequest"/>
            <wsdl:output message="tns:bookYearResponse"/>

    <wsdl:binding name="Library" type="tns:Library">
        <soap:binding style="rpc" transport=""/>
        <wsdl:operation name="bookYear">
            <soap:operation soapAction=""/>
                <soap:body use="literal" namespace="Library"/>
                <soap:body use="literal" namespace="Library"/>

    <wsdl:service name="Library">
        <wsdl:port binding="tns:Library" name="BookLibrary">
            <soap:address location=""/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment