Create a PHP webservice in 5min, Using PHP, SOAP and WSDL Technology , NuSOAP

Posted: November 25, 2009 in Technology

Introduction
Unless you have been living in a cave somewhere without Internet access for the last few years, you have undoubtedly heard of XML, SOAP and Multi-Tiered Application Programming. If you are like many programmers, including myself, you were quite taken aback by these ideas and technologies. You may have gone so far as to simply dismiss them as irrelevant to your skill set. It’s time to wake up and realize they’re hereto stay… and for good reason!.

XML and SOAP, and in turn Multi-Tiered Programming, are technologies that can take you from being a run of the mill code hacker to a professional application developer that actually builds cool things that work and which other people can work on. These technologies enable you to build applications that separate data from presentation, keep things organized and enable your application to scale as your needs and user base increases.

If you believe like I do that the Internet is the ultimate building ground of our future,then you have to see that the ‘hackish’ method in which most applications for the web are built and designed is pitiful. I know that I am quite guilty of it, myself. Many times I get an itch and I just scratch it without thinking of what the future holds or the maintainability of my application. Sure the job gets done; the itch has gone away momentarily. But when the itch comes back six months down the road and I have to add or modify features, I am utterly disappointed in myself over the sorry shape of my code.
You may be asking, how can XML and SOAP help me to avoid poor application design? Well, by themselves they won’t help at all. First and foremost you must get yourself into the mind set that it needs to take place. XML and SOAP are just two tools that will allow you to accomplish your goal.

Today we will build a Web Service using SOAP. In doing so, I hope that you will become familiar with the technology so that you can start incorporating it into your future applications.

Definitions
Before we get too much further along, let’s make sure we are all on the same footing regarding the basic terminology that we will deal with in this tutorial.

*XML: “XML is the Extensible Markup Language. It is designed to improve the functionality of the Web by providing more flexible and adaptable information identification.” (http://www.ucc.ie/xml/#acro) http://www.ucc.ie/xml/#acro) In other words, XML is a method for describing your data. For the purpose of this tutorial, we will not be directly manipulating any

XML. Instead, we will examine the XML resulting from our scripts. The libraries and protocols we will use through this tutorial will handle the XML manipulation for us.

*SOAP: Simple Object Access Protocol. “SOAP is a lightweight protocol for exchange of information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in
a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses.” ((http://www.w3.org/TR/2000/NOTE-SOAP-20000508/) http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)

SOAP is what you are here for. We will develop both a client and a server for our SOAP service. In this tutorial, we will be using the NuSOAP library. ((http://dietrich.ganx4.com/nusoap/index.php)http://dietrich.ganx4.com/nusoap/index.php)

*WSDL: “WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.”
((http://www.w3.org/TR/wsdl) http://www.w3.org/TR/wsdl) As with XML, we will not be directly any WSDL documents. The wonderful NuSOAP library will generate WSDL documents for us. What
you need to know about WSDL is that it is a document that describes a Web Service. It can tell a client how to interact with the Web Service and what interfaces that Web Service provides.

*Client: We will define a Client as a script that uses a Web Service.
*Server: Conversely, a Server will be defined as a script that provides a Web Service.

Define Our Goal
Today we are going to build a Web Service that will return a stock price given a particular stock symbol. This is a classic example of where Web Services are of great use. You may be building an application that needs the data and could very easily just pull the data directly from your data source. Building a Web Service for it, however, allows give other applications easy access the same data in the future. It also separates the data extraction from the data source from the application itself. Say you were storing the data in a MySQL database but later decided to move it to a SQLite database… in this scenario your application wouldn’t know the difference. Its calls to the Web Service remain unchanged.
To provide a stock quote service you will have to have the stock prices and symbols stored in some fashion or another. This tutorial is not going to concentrate on the storage mechanism or how to obtain the prices. I will simply provide you will a table schema and some sample data to work with.

CREATE TABLE `stockprices` (
`stock_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`stock_symbol` CHAR( 3 ) NOT NULL ,
`stock_price` DECIMAL(8,2) NOT NULL ,
PRIMARY KEY ( `stock_id` )
);
INSERT INTO `stockprices` VALUES (1, ‘ABC’, ‘75.00’);
INSERT INTO `stockprices` VALUES (2, ‘DEF’, ‘45.00’);
INSERT INTO `stockprices` VALUES (3, ‘GHI’, ‘12.00’);
INSERT INTO `stockprices` VALUES (4, ‘JKL’, ‘34.00’);

Create a SOAP server
The first thing we need to do is to create the SOAP server. This is the script that will fetch the data from the database and then deliver it to the Client. One wonderful thing about the NuSOAP library is that this same Server script will also create a WSDL document for us.

The first step is to create a function that will fetch the data we want. Create this function just as you would any other. It is just straight up PHP. The one trick is to name the function something sensible, as this will be the name that is used when the Client contacts the Server.

Now, it is time to turn this function into a Web Service. Basically, all we have to do is include the NuSOAP library, instantiate the soap_server class and then register the function with the server. Let’s go through it step by step, after which I will present the completed script.

The first thing necessary is to simply include the NuSOAP library.

require(‘nusoap.php’);

Next, instantiate an instance of the soap_server class.

$server = new soap_server();

create for us. Specifically we specify the name of the server and the namespace, in that order.

$server->configureWSDL(‘stockserver’, ‘urn:stockquote’);

Now, we register the function we created with the SOAP server. We pass several different parameters to the register method. The first is the name of the function we are registering.
The next parameter specifies the input parameters to the function we are registering. Notice that it is an array. The keys of the array represent the names of the input parameters, while the value specifies the type of the input parameter. One thing that pure PHP programmers might find odd is that I had to specify what types my input and return parameters are with the designations of xsd:string and xsd:decimal. It is required that you describe your data properly. You are not dealing with a loosely typed language here. The third parameter to the register method specifies the return type of the registered function. As shown below, it is fashioned in the same way as the last parameter, as an array. The next two parameters specify the namespace we are operating in, and the SOAPAction. For more information on the SOAPAction see (http://www.oreillynet.com/pub/wlg/2331) http://www.oreillynet.com/pub/wlg/2331.

$server->register(“getStockQuote”,
array(‘symbol’ => ‘xsd:string’),
array(‘return’ => ‘xsd:decimal’),
‘urn:stockquote’,
‘urn:stockquote#getStockQuote’);

Now, we finally finish it off with two more lines of code. The first simply checks if $HTTP_RAW_POST_DATA is initialized. If it is not, it initializes it with an empty string. The next line actually calls the service. The web request is passed to the service from the $HTTP_RAW_POST_DATA variable and all the magic behind the scenes takes place.

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
? $HTTP_RAW_POST_DATA : ”;
$server->service($HTTP_RAW_POST_DATA);

Here is the completed server script which I have saved in a file named stockserver.php.

configureWSDL(‘stockserver’, ‘urn:stockquote’);
$server->register(“getStockQuote”,
array(‘symbol’ => ‘xsd:string’),
array(‘return’ => ‘xsd:decimal’),
‘urn:stockquote’,
‘urn:stockquote#getStockQuote’);
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
? $HTTP_RAW_POST_DATA : ”;
$server->service($HTTP_RAW_POST_DATA);
?>

The WSDL Document
At this point you have a fully functioning SOAP Server. Clients can connect to it and request data. If you haven’t done so already, bring up the script in your browser and see what you get. You should get a page giving you a link to the WSDL document for the Server. Click on it and you should see the resulting WSDL document. Surprise, surprise, it is in XML! If you read over this document, you will see that it describes what happens for a request and as a response for your particular SOAP Service.

Note that while it is possible to create a SOAP Server without having it create the WSDL file, I recommend creating the WSDL document anyway. It is simple enough, so why not?

Creating a SOAP Client
Creating a SOAP Client to access our Server with is just as simple as creating the Server was. Understand though that the Client does not necessarily need to be a PHP Client. The SOAP Server we just created can be connected to by any type of Client, whether that be Java, C#, C++, etc.

To create the SOAP Client, all we need to do are three things. First, include the NuSOAP library. This is done just as it was for the Server.

require_once(‘nusoap.php’);

Secondly, we need to instantiate the soapclient class. We pass in the URL of the SOAP Server we are dealing with.

$c = new soapclient(‘http://localhost/stockserver.php’);

Last make a call to the Web Service. The one caveat is that the parameters to the Web Service must be encapsulated in an array in which the keys are the names defined for the service. You will see that I have an array key named ‘symbol’ because that is the name of the input parameter of my function. If you remember how we specified the input parameters when we registered the function with the server, you will see that this is very similar.

$stockprice = $c->call(‘getStockQuote’,
array(‘symbol’ => ‘ABC’));

Now, here is the completed Client script, which I have saved in a file named stockclient.php.

call(‘getStockQuote’,
array(‘symbol’ => ‘ABC’));
echo “The stock price for ‘ABC’ is $stockprice.”;
?>

There it is. It really is that simple.

Conclusion
Hopefully after reading through this tutorial you have an understanding of how simple it is to create a SOAP Server and Client with NuSOAP. It simply astonished me how utterly simple it was after I actually took a look at it! Before I ever laid eyes on it I had dreams of a complex system that would take months to utilize. Luckily, NuSOAP came along and made that task simpler than anyone could ever ask for.

As you can see, SOAP is a wonderful tool for separating your application into smaller more manageable pieces. Do realize that SOAP isn’t the cure all for everything. Its overuse is just as bad as any other poor design. The key to a good application design is patience and planning. Sit down, take out the old pencil and paper and write things down. Understand what you are really getting yourself into and ask lots of ‘What If’ questions. Think about the future of the application and ask yourself about the different ways it may be used in the future. The number one pitfall of application design is painting yourself into a corner. If you just thought about it ahead of time you could have started at the other side of the room.

Comments
  1. Brandon says:

    Great blog its very helpful and easy to understand. Most of these blogs are tutorials that you can repost just be sure to reference the page you get them from if adding them to your blog. Again thank you for this blog.

  2. Pooja says:

    The SOAP service requires an XML wrapper around every request and response.so Once namespaces and typing are declared, a four- or five-digit stock quote in a SOAP response could require more than 10 times as many bytes as would the same response in REST. The which technology would be better to use? SOAP/ REST/ NuSoap ? anyone can help me out to come out with this critic!! thanks in advance.

  3. Cesar says:

    This one of the best SOAP service tutorials on the web for newbies! Amazing job, many thanks!

  4. rohit says:

    hi It’s really confusing . this code only u can understand . u dont mentation step how to run this . Your code is not for the beginner . i am beginner of php .

  5. Milap says:

    Thanks for your post , nice explanation..

  6. Vishal says:

    actually i m also a beginner and i was follow the step given above but…. it cant work…. so please clarify if any step will be not added into this….. please…..

  7. Helmi says:

    first, the title is offensive. thought i’m stupid from not understanding here for 5 mins, you should mention that this not for beginner. Nevertheless, it’s nice post, i worked on wsdl quite recently, but not building a web service, working one, as client, connecting SOAP server. hope can learn how to build one.

  8. kartika says:

    Excellent blog! Thanks for the clear explanation.

  9. Fabiyi Adeolu says:

    Thanks guy it really took out the bugs in my eyes. Bless you.

  10. kribo says:

    After hours searching the web I finally found a howto that makes sence.
    gratz dude….
    One could fine tune the post with a zip file…

  11. Madhu says:

    it would be gr8 if anyone put all the code and provide to users as an example to download

  12. GHoSt says:

    “Now, here is the completed Client script, which I have saved in a file named stockclient.php.

    call(‘getStockQuote’,
    array(‘symbol’ => ‘ABC’));
    echo “The stock price for ‘ABC’ is $stockprice.”;
    ?>”

    Sry, but this can’t be the complete script, as you mentioned some other things before. Hopefully everyone can see, that the <?PHP Tag is missing. I'm not a beginner in PHP, but this can confuse beginners.

    The complete script (haven't tested this tutorial) should be:
    call(‘getStockQuote’,
    array(‘symbol’ => ‘ABC’));
    echo “The stock price for ‘ABC’ is $stockprice.”;
    ?>

  13. Daniel says:

    Apologies for my ignorance here.
    I have created a server.php file that contains:
    configureWSDL(‘server’, ‘urn:server’);
    //register a function that works on server
    $server ->register(‘SayHello’, array(‘name’ => ‘xsd:string’), array(‘return’ => ‘xsd:string’), ‘urn:server’, ‘urn:server# SayHello’);

    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ”;
    $server ->service($HTTP_RAW_POST_DATA);
    ?>
    —————————————————————–
    I have created a client.php file that contains:
    call(‘SayHello’, array(‘name’=>’Daniel’));
    echo $myString;
    ?>

    Where exactly do I include the actual function?

    Thanks!

    • Daniel says:

      I think i have pasted the wron server code i actually created.
      Here it is:
      configureWSDL(‘server’, ‘urn:server’);
      //register a function that works on server
      $server ->register(‘SayHello’, array(‘name’ => ‘xsd:string’), array(‘return’ => ‘xsd:string’), ‘urn:server’, ‘urn:server# SayHello’);

      $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ”;
      $server ->service($HTTP_RAW_POST_DATA);
      ?>

      Thanks a lot for your help!

      • Daniel says:

        Sorry buddy. Its me again. I feel a bit frustrated so sorry for rewriting again.
        I found where to put my function… but still pulling my hair to make it work.
        Here is what i have for server:
        ———————————————————-
        configureWSDL(‘server’, ‘urn:server’);
        //register a function that works on server
        $server ->register(‘SayHello’, array(‘name’ => ‘xsd:string’), array(‘return’ => ‘xsd:string’), ‘urn:server’, ‘urn:server# SayHello’);

        function SayHello($name){
        $name=utf8_decode($name);
        if($name==”)
        $name=’unknown’;
        return utf8_encode(‘Hello ‘.$name.’!’);
        }

        $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ”;
        $server ->service($HTTP_RAW_POST_DATA);
        ?>

        ————————————————————-
        here is my generated wsdl:
        ————————————————————-





        ————————————————————-
        And here is what i have for client:
        ————————————————————-
        call(‘SayHello’, array(‘name’ => ‘Daniel’));
        echo $result;
        ?>
        ————————————————————-
        I am losing my hopes towards working with webservices in php. So really hope you can shed some light.

        Thanks!

        Daniel

  14. Johnny says:

    Add this:
    When instantiating a new soap-client in the client-script you need to add ?wdsl, like so:
    $c = new soapclient(‘http://localhost/stockserver.php?wdsl’);

  15. Hi, if you could try the generator WsdlToPhp on the website http://www.wsdltophp.com, I would be pleased to have your feedbacks,

    regards

  16. edwin says:

    how comes am getting syntax error, unexpected :

  17. Every weekend i used to pay a visit this web page, for the reason that i want enjoyment, since this this web site conations actually good
    funny data too.

  18. Arnab Biswas says:

    Yet another post…it served like a treat to my learning of WebServices…

  19. smile says:

    hai..i am very new to PHP…it is very helpful for me… nice explanation ..but…really confused with u’r coding matearial…

  20. Hi there terrific blog! Does running a blog similar to this require a
    lot of work? I’ve no knowledge of computer programming however I was hoping to start my own blog in the near future. Anyhow, if you have any suggestions or techniques for new blog owners please share. I know this is off topic however I just had to ask. Cheers!

  21. Terry says:

    The sort of golf clubs which you end up selecting should match with the child’s current height and factor in some growth as well.
    A good set of golf clubs can dramatically increase your play.
    Wit this versatility, they can be used almost anywhere on the golf course.

  22. Tersem kaur says:

    Hi there. Could I please know what environment can I create the codes in and where can I validate them? I am very new to this and would like some guidance,thanks. I was thinking of JavaBeans but wanted to bounce this off you.

  23. Zion M'Lo says:

    tutorial mal feito.

  24. Ano Van says:

    good tutorial, it simple create to beginnner,
    thanks http://www.pasarkode.com

Leave a reply to Ano Van Cancel reply