Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.
You’ll see how use the NuSOAP library to write a simple PHP Web service server and client in the first part of the article. In the second part, you will see how to write a PHP Web service server and a JavaScript client to use it using the AJAX technology and the SOAP protocol.
Learn PHP and Start your Free Trial today!
The NuSOAP library is a collection of PHP classes that is used for sending and receiving SOAP messages using the HTTP protocol. The NuSOAP library can be downloaded from the Sourceforge link. To use the NuSOAP classes in your PHP source files, you should include the following code line:
require_once('./nusoap-0.9.5/lib/nusoap.php');
Writing a Web Service Server
In the first part of this article, we will create a simple Web service server-client “hello” example. The server we’ll develop with NuSOAP exposes one method, named hello.
// Implement the "hello" method as a PHP functionfunction hello($username) { return 'Hello, '.$username.'!';}
One of the useful features of NuSOAP is used to verify that a Web service exists and ensures that it exposes the method you need, in this case hello method. For example, testing in a browser, the http://localhost/server.php link reveals the Web service WSDL for the Web service you just created, and the service method. Next, you can see that, for the hello method, you can see a list containing the information you need to write a proper Web service client.
server.php
<?phprequire_once('./nusoap-0.9.5/lib/nusoap.php');// Create the server instance$server = new soap_server();$server->configureWSDL('server', 'urn:server');$server->wsdl->schemaTargetNamespace = 'urn:server';// SOAP complex type return type (an array/struct)$server->wsdl->addComplexType( 'Person', 'complexType', 'struct', 'all', '', array('id_user' => array('name' => 'id_user', 'type' => 'xsd:int')));// Register the "hello" method to expose it$server->register('hello', array('username' => 'xsd:string'), // parameter array('return' => 'xsd:string'), // output 'urn:server', // namespace 'urn:server#helloServer', // soapaction 'rpc', // style 'encoded', // use 'Just say hello'); // description// Implement the "hello" method as a PHP functionfunction hello($username) { return 'Hello, '.$username.'!';}// Use the request to invoke the service$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';$server->service($HTTP_RAW_POST_DATA);?>
Figure 1 shows a screenshot of the WSDL and the method for the server.php sample Web service.
Figure 1: The WSDL and the method for the server.php sample Web service
Writing a Web Service Client
After the Web service server is completed and verified, you can write a NuSOAP Web service client. This is a simpler process than writing an Web service server, as you will see in the next listing, named client.php. You may notice that in the following listing a client instance is created by instantiating the nusoap_client class, and to call the Web service method you should use the NuSOAP call method.
client.php
<?phprequire_once('./nusoap-0.9.5/lib/nusoap.php');// This is your Web service server WSDL URL address$wsdl = "http://localhost/server.php?wsdl";// Create client object$client = new nusoap_client($wsdl, 'wsdl');$err = $client->getError();if ($err) { // Display the error echo '<h2>Constructor error</h2>' . $err; // At this point, you know the call that follows will fail exit();}// Call the hello method$result1=$client->call('hello', array('username'=>'John'));print_r($result1).'n';?>
Now, testing the client into the browser, you should see the message shown in Figure 2:
Figure 2: The message received after testing the client in a browser
Writing a JavaScript Web Service Client
In the second part of the article, we will create a browser Web service client for converting EUR to USD in JavaScript. It uses AJAX technologies for the CurrencyConverter method. In this case, our server developed with NuSOAP exposes the CurrencyConverter method listed below:
// Define the CurrencyConverter method as// a PHP functionfunction CurrencyConverter($amount, $rate) { return 'The currency converter EUR to USD is:'.($amount*$rate);}
This section describes how to create a browser Web service client in JavaScript that uses AJAX technologies for the CurrencyConverter method. To do that, we will need an HTML interface (index.html), a JavaScript code (ajaxSOAP.js), a Web service server (server.php), and a Web service client (client.php).
First, we need to write a simple HTML interface that lets a user specify values for the amount and exchange rate arguments of the CurrencyConverter method. Those values are passed to a JavaScript function named exchangeAjax, placed into the JavaScript listing named ajaxSOAP.js. At the bottom of the HTML interface, an empty <div> tag appears, which AJAX will fill with the response received from the Web service server:
<div class="ui-grid ui-grid-responsive" id="resultDiv"></div>
index.html
<!DOCTYPE html><html> <head> <title>Web Service SOAP and AJAX</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/ 1.11.3/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/ jqueryui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript" src="development/x-tag-core.min.js"></script> <script type="text/javascript" src="development/primeui.min.js"></script> <script type="text/javascript" src="development/primeelements.min.js"></script> <script type="text/javascript" src="./ajaxSOAP.js"></script> <link type="text/css" href="development/font-awesome/css/font-awesome.min.css" rel="stylesheet"/> <link type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/ 1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"> <link type="text/css" href="development/primeui.min.css" rel="stylesheet"> <link type="text/css" href="development/themes/excite-bike/theme.css" rel="stylesheet"/> <style type="text/css"> .ui-widget { font-family: Rockwell, 'Courier Bold', Courier, Georgia, Times, 'Times New Roman', serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: 400; line-height: 20px; } .ui-widget-content { margin-top: 5px; } </style> </head> <body> <h2><p style="color:darkblue"><b>Currency Converter </b></h2> <div class="ui-grid ui-grid-responsive"> <div class="ui-grid-row"> <div class="ui-grid-col-4"> <form> <p-fieldset toggleable> <legend>EUR to USD</legend> <div class="ui-grid ui-grid-responsive"> <div class="ui-grid-row"> <div class="ui-grid-col-4">Amount::</div> <div class="ui-grid-col-4"> <input id="amount_id" type="text" is="p-inputtext" size="20" required autofocus /> </div> </div> <div class="ui-grid-row"> <div class="ui-grid-col-4">Exchange rate::</div> <div class="ui-grid-col-4"> <input id="rate_id" type="text" is="p-inputtext" size="20" required autofocus /> </div> </div> <button is="p-button" icon="fa-pencil-square-o" type="button" value="Convert" style="margin-top:5px;" onclick="exchangeAjax();">Convert</button> <p></p> <div class="ui-grid ui-grid-responsive" id="resultDiv"></div> </div> </p-fieldset> </form> </div> </div> </div> </body></html>
Testing the above HTML interface in the browser, we should get something like what’s shown in Figure 3:
Figure 3: Testing the preceding HTML interface in a browser
Notice that the index.html listing doesn’t provide any implementation for the exchangeAjax() method; for that, we will need the ajaxSOAP.js script. This JavaScript module will be saved in the same folder as the preceding HTML code.
The exchangeAjax function begins by extracting the arguments that should be passed to the Web service server. Remember that users provide the argument’s values through the HTML interface, so you have to access the two text fields identified by the IDs amount_id and rate_id. To do that, we will use the next two code lines:
var amount_var = document.getElementById("amount_id").value; var rate_var = document.getElementById("rate_id").value;
After receiving the values, we need to write the SOAP message that calls the CurrencyConverter method, passing it the two values that the service needs to calculate the EUR to USD exchange. The SOAP message is stored into a JavaScript variable, and then the AJAX mechanism is implemented by obtaining an XMLHttpRequest object, and continues by opening a POST channel on the server’s URL (server.php, listed later in this section), indicating the AJAX callback function, named callbackAjax. Following is the complete JavaScript code:
ajaxSOAP.js
var httpRequest = null;var xhrTimeout = null;var url = "http://localhost/server.php";var soapMessage = null;function exchangeAjax(){ // Extract the arguments that should be passed to // the Web service server var amount_var = document.getElementById("amount_id").value; var rate_var = document.getElementById("rate_id").value; // Write the SOAP message that calls the CurrencyConverter method // and passes it the two values that the service needs to // calculate the EUR to USD exchange. The SOAP message is stored // into a JavaScript variable. soapMessage = "<?xml version='1.0' encoding='UTF-8'?>"; soapMessage = soapMessage + "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle= 'http://schemas.xmlsoap.org/soap/encoding/' "; soapMessage = soapMessage + "xmlns:SOAP-ENV= 'http://schemas.xmlsoap.org/soap/envelope/' "; soapMessage = soapMessage + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "; soapMessage = soapMessage + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "; soapMessage = soapMessage + "xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' "; soapMessage = soapMessage + "xmlns:tns='urn:mathwsdl'>"; soapMessage = soapMessage + "<SOAP-ENV:Body><tns:CurrencyConverter xmlns_tns='urn:mathwsdl'> <amount xsi_type='xsd:int'>" +amount_var+"</amount>"; soapMessage = soapMessage + "<rate xsi_type='xsd:float'>" +rate_var+"</rate>"; soapMessage = soapMessage + "</tns:CurrencyConverter></SOAP-ENV:Body></SOAP-ENV:Envelope>"; // Implement the AJAX mechanism if(window.XMLHttpRequest) { httpRequest=new XMLHttpRequest(); } else if (window.ActiveXObject) { httpRequest=new ActiveXObject("Microsoft.XMLHTTP"); } httpRequest.open("POST",url,true); if (httpRequest.overrideMimeType) { httpRequest.overrideMimeType("text/xml"); } httpRequest.onreadystatechange=callbackAjax; httpRequest.setRequestHeader("Man", "POST http://server.php HTTP/1.1") httpRequest.setRequestHeader("MessageType", "CALL"); httpRequest.setRequestHeader("Content-Type", "text/xml"); httpRequest.send(soapMessage); xhrTimeout=setTimeout("ajaxTimeout(httpRequest);",120000);}function callbackAjax(){ try { if(httpRequest.readyState==4) { if(httpRequest.status==200) { clearTimeout(xhrTimeout); resultDiv=document.getElementById("resultDiv"); resultDiv.style.display='inline'; resultDiv.innerHTML='<font color="#000080" size="4"> <b>' + httpRequest.responseText+'</b></font>'; } } }catch(e) { alert("Error!"+e); } }function ajaxTimeout(ajaxOBJ) { ajaxOBJ.abort();}
Next, we need to write our Web services server and client (server.php and client.php). Notice that they are pretty similar to the example from the previous section, the Hello example; the main difference is that, in this case, our server exposes the CurrencyConverter method, which in this case take two arguments: amount and rate (exchange rate) and calculates the EUR to USD currency converter using the amount*rate formula, using the following PHP method:
// Define the CurrencyConverter method as a PHP functionfunction CurrencyConverter($amount, $rate) { return 'The currency converter EUR to USD is:'.($amount*$rate);}
server.php
<?php// Pull in the NuSOAP coderequire_once('./nusoap-0.9.5/lib/nusoap.php');// Create the server instance$server = new soap_server();// Initialize WSDL support$server->configureWSDL('mathwsdl', 'urn:mathwsdl');// Register the CurrencyConverter method to expose its// method name$server->register('CurrencyConverter',// input parametersarray('amount' => 'xsd:int', 'rate' => 'xsd:float'),// output parametersarray('CurrencyConverter' => 'xsd:string'), // namespace 'urn:mathwsdl', // soapaction 'urn:CurrencyConverterwsdl#CurrencyConverter', 'rpc', // style 'encoded', // use // documentation 'Calculate the currency converter EUR to USD as (amount*rate)');// Define the CurrencyConverter method as a// PHP functionfunction CurrencyConverter($amount, $rate) { return 'The currency converter EUR to USD is:'.($amount*$rate);}// Use the request to invoke the service$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';$server->service($HTTP_RAW_POST_DATA);?>
After testing the server.php listing in a browser, you should get something like this:
Figure 4: After testing the server.php listing in a browser
After the Web service server is completed and verified, we can write a NuSOAP Web service client. The client instance is created by instantiating the nusoap_client class and, to call the Web service method, you should use the NuSOAP call method.
client.php
<?php// Pull in the NuSOAP coderequire_once('./nusoap-0.9.5/lib/nusoap.php');// Create the client instance$client = new nusoap_client('http://localhost/server.php?wsdl', true);// Check for an error$err = $client->getError();if ($err) { // Display the error echo '<h2>Constructor error</h2><pre>' . $err . '</pre>'; // At this point, you know the call that follows will fail}// Call the CurrencyConverter SOAP method$result = $client->call('CurrencyConverter', array('amount' => 123, 'rate' => 2.08));// Check for a faultif ($client->fault) { echo '<h2>Fault</h2><pre>'; print_r($result); echo '</pre>';else { // Check for errors $err = $client->getError(); if ($err) { // Display the error echo '<h2>Error</h2><pre>' . $err . '</pre>'; } else { // Display the result echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>'; }}?>
Now, it is time to test the JavaScript/AJAX client. Open your browser and browse to the index.html file. After inserting the two values for amount and exchange rate and pressing the Convert button, you should see something similar to Figure 5:
Figure 5: Executing a currency conversion
Conclusion
Calling Web services from AJAX is an interesting practice, and putting the two together is a good fusion that will help you build cool, interactive Web sites.
FAQs
How to create and consume web service with PHP? ›
php require_once('nusoap. php'); $wsdl="http://localhost/server.php?wsdl"; $client=new soapclient($wsdl, 'wsdl'); Next step, we create a set of parameters to pass into the Web service and then remotely call the CalculateOntarioTax method.
What is NuSOAP in Web services? ›The NuSOAP library is a collection of PHP classes that is used for sending and receiving SOAP messages using the HTTP protocol. The NuSOAP library can be downloaded from the Sourceforge link.
How to create SOAP web service in PHP? ›- Copy the PHPToolkit directory to the directory in your IDE where your project resides.
- Edit the NSconfig. ...
- If SOAP logging is required, create a folder called nslog inside the PHPToolkit folder.
Calling a SOAP Service
PHP5's built-in SOAP client, ext/soap is a pretty easy to way to consume SOAP web services. Assuming your SOAP web service has a WSDL file, you just instantiate a SOAP client with the WSDL file, and the client will make an object with methods for each method offered by the WSDL file.
- Create a REST API.
- Create a HTML form.
- Include jQuery and Bootstrap library.
- Use AJAX method to pass data.
- Make API call and retrieve data using PHP cURL.
Difference Between Web Service vs Web API:
Web service is used to communicate between two machines on a network. Web API is used as an interface between two different applications for communicating with each other. It uses HTML requests that can be compressed, but XML data cannot be compressed. Data can be compressed.
I'd say that web applications are intended for users and web services are intended for other applications. That's the most important difference. Web applications usually present data in HTML which looks nice to the user and web services usually present data in XML which easy to parse by other applications.
What is the difference between Webapp and web service? ›A Web Application is meant for humans to read, while a Web Service is meant for computers to read. Web Application is a complete Application with a Graphical User Interface (GUI), however, web services do not necessarily have a user interface since it is used as a component in an application.
How do I create and consume a web API? ›- Right-click the Controllers folder.
- Select Add > New Scaffolded Item.
- Select API Controller with actions, using Entity Framework, and then select Add.
- In the Add API Controller with actions, using Entity Framework dialog: Select TodoItem (TodoApi.Models) in the Model class.
- Create a Database & table. Create a database & table in MySQL to store the data. ...
- Create config.php script. This PHP script will store database connection-related information. ...
- Create a PHP script add-to-do. php to add To-Do's. ...
- Create a PHP script info.php to fetch To-Do information from the list of To-Do's.
How to create service in PHP? ›
- SOAP (Simple Object Access Protocol) ...
- REST (Representational State Transfer) ...
- POST : Create a new resource.
- PUT : Update a particular resource by an id.
- DELETE : Remove a particular resource.
- Example of POST.
Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML. Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.