Web Service Example
Any application can have a Web Service component.
The creation of a Web Service is independent of the programming language used.
In this section, we will introduce how to create a Web Service using the SOAP extension in PHP.
SOAP has two operation modes: NO-WSDL and WSDL.
- NO-WSDL Mode: Uses parameters to pass the required information.
- WSDL Mode: Uses the WSDL file name as a parameter and extracts the necessary information for the service from the WSDL.
An Example: PHP Web Service
Before starting the example, we need to ensure that the SOAP extension is installed in PHP. Checking phpinfo, the following information indicates that the SOAP extension is installed:
In this example, we will use PHP SOAP to create a simple Web Service.
The server Server.php file code is as follows:
<?php
// SiteInfo class to handle requests
Class SiteInfo
{
/**
* Returns the website name
* @return string
*/
public function getName(){
return "tutorialpro.org";
}
public function getUrl(){
return "www.tutorialpro.org";
}
}
// Create SoapServer object
$s = new SoapServer(null, array("location"=>"http://localhost/soap/Server.php", "uri"=>"Server.php"));
// Export all functions from the SiteInfo class
$s->setClass("SiteInfo");
// Process a SOAP request, call the necessary functions, and send back a response.
$s->handle();
?>
The client Client.php file code is as follows:
<?php
try{
// non-wsdl mode to call web service
// Create SoapClient object
$soap = new SoapClient(null, array('location'=>"http://localhost/soap/Server.php", 'uri'=>'Server.php'));
// Call functions
$result1 = $soap->getName();
$result2 = $soap->__soapCall("getUrl", array());
echo $result1."<br/>";
echo $result2;
} catch(SoapFault $e){
echo $e->getMessage();
}catch(Exception $e){
echo $e->getMessage();
}
At this point, when we access http://localhost/soap/Client.php, the output is as follows: