The simplest PHP Web Service Client

Wednesday, January 2, 2008

Yesterday I showed how to write a very simple Web service, form the article that I am currently writing.

Here is the simplest client, extracted form the same ongoing article.

  1. <?php

  2. $reqestPayloadString = <<<XML
  3. <knock>Knock, knock!!!</knock>
  4. XML;
  6. $client = new WSClient(array("to" => "http://localhost/tutorial/first/service.php"));

  7. $response = $client->request($reqestPayloadString);

  8. echo "Service replied asking: '".$response->str."'\n";

  9. ?>

As in the case of the service, the client code is also very simple. The steps used in the client when consuming the service could be summarized as follows.

  1. Create the client instance with the service endpoint address (line 7)
  2. Send the request with the request message (line 9)
  3. Process the received response (line 11)

In this Web service client, when the WSClient instance is created, on line 7, we provide the endpoint address of the service we want to consume as the to option. The address used in this sample is the address of the service that we deployed in the previous section.

Form lines 3 to 5, we define the XML string to be sent as the request.

On line 9, the call to request() method of the WSClient instance, with the request XML string as a parameter, triggers the service invocation. Upon the call to request() method, Web service client forms the request message with the given XML string, sends the request to the service given in the to address and receives the response and stores the response in the WSMessage instance named response. You can access the incoming response as an XML string using the str member variable of the WSMessage instance.

No comments: