How to implement WebService using SOAP extension in PHP

高洛峰
Release: 2023-03-05 10:10:01
Original
1088 people have browsed it

The example of this article describes how PHP uses SOAP extension to implement WebService. Share it with everyone for your reference. The details are as follows:

Recently, the external interface in a PHP project involves WebService. There are not many related articles on search engines. Most of the ones I find refer to NuSOAP, an open source software that is said to be very powerful. (Download address: http://sourceforge.net/projects/nusoap/), that is, some classes. The environment described in the article is PHP 4.3, and now PHP 5.2 or PHP 5.3 is popular. I tried it first and ran it wrong. It turns out that the soapclient class provided by NuSOAP conflicts with the new built-in SOAP extension SoapClient class in PHP 5.

Although NuSOAP claims to be used in all PHP environments, it is not affected by server security settings. However, since a lot of class files need to be referenced, I still think it would be better to use the built-in SOAP extension added in PHP 5, as long as it is practical. First understand SOAP:

1. Comparison between SOAP and XML-PRC

In the early days of the development of Web services, the first major use of XML formatted messages was to apply to the XML-RPC protocol , where RPC stands for remote procedure call. In XML Remote Procedure Call (XML-RPC), the client sends a specific message that must include the name, the program running the service, and the input parameters.

XML-RPC can only use limited types of data types and some simple data structures. People thought that this protocol was not powerful enough, so SOAP appeared - its original definition was Simple Object Access Protocol. After that, everyone gradually realized that SOAP is not simple, and there is no need to use an object-oriented language, so now people just use the name SOAP.

XML-RPC only has a simple set of data types. Instead, SOAP defines data types by leveraging the continuous evolution of XML Schema. At the same time, SOAP can also utilize XML namespaces, which is not required by XML-RPC. This allows the beginning of a SOAP message to be any type of XML namespace declaration, at the cost of adding more complexity and incompatibility between systems.

With the awakening of the computer industry, people discovered the business potential of XML-based Web services, so companies began to continuously explore ideas, opinions, arguments, and standardization attempts. W3C once tried to organize an achievement exhibition under the name of "Web Services Activities", which also included the XML Protocol Working Group (XML Protocol Working Group) that actually made SOAP. The number of standardization efforts related to Web services that are in some way related to or dependent on SOAP has doubled to an astonishing degree.

Originally, SOAP was developed as an extension of XML-RPC. Its main emphasis is to make remote procedure calls through method and variable names obtained from WSDL files. Now, through continuous advancement, people have found more ways to use SOAP than just the "file" method - basically using a SOAP envelope to send XML formatted files. In any case, to master SOAP, it is fundamental to understand the role played by WSDL.

2. SOAP packet structure analysis

SOAP message is called a SOAP Envelope, including SOAP Header and SOAP Body. Among them, SOAP Header can easily insert various other messages to expand the functions of Web Service, such as Security (using certificates to access Web Service), and SOAP Body is the specific message text, which is the information after Marshall.

When SOAP is called, it means sending an HTTP Post message to a URL (such as http://api.google.com/search/beta2) (according to the SOAP specification, HTTP Get messages can also be supported ), the name of the calling method is given in the HTTP Request Header SOAP-Action, and the next step is the SOAP Envelope. The server receives the request, performs the calculation, Marshalls the returned result into XML, and returns it to the client using HTTP.

3. Simple SOAP example

There are generally three options for SOAP development:

1), PEAR’s own SOAP extension;
2), PHP’s own SOAP extension;
3), NuSOAP (pure PHP).

New in PHP 5 are built-in SOAP extensions, which are provided as part of PHP, so there is no need to download, install and manage separate packages. This is the first SOAP implementation written in C instead of PHP for PHP, so the author claims it is significantly faster. Relevant documentation is included in the Function Reference section of the PHP manual (php_soap.dll).

An example of a client accessing .NET WEB service:

< ? php
$objSoapClient = new SoapClient("http://www.webservicemart.com/uszip.asmx?WSDL");
$param = array("ZipCode"=>'12209');
$out = $objSoapClient->ValidateZip($param);
$data = $out->ValidateZipResult;
echo $data;
?>
Copy after login

4. Example

1), using PHP to establish a SOAP service

Create soap_server.php (virtual path is: http://localhost/php/soap/soap_server.php)

< ? php
/**
* A simple math utility class
*/
class math{
  /**
  * Add two integers together
  *
  * @param integer $a The first integer of the addition
  * @param integer $b The second integer of the addition
  * @return integer The sum of the provided integers
  */
  public function add($a, $b){
    return $a + $b;
  }
  /**
  * Subtract two integers from each other
  *
  * @param integer $a The first integer of the subtraction
  * @param integer $b The second integer of the subtraction
  * @return integer The difference of the provided integers
  */
  public function sub($a, $b){
    return $a - $b;
  }
  /**
  * Div two integers from each other
  *
  * @param integer $a The first integer of the subtraction
  * @param integer $b The second integer of the subtraction
  * @return double The difference of the provided integers
  */
  public function div($a, $b){
    if($b == 0){
      throw new SoapFault(-1, "Cannot divide by zero!");
    }
    return $a / $b;
  }
}
$server = new SoapServer('math.wsdl', array('soap_version'=>SOAP_1_2));
$server->setClass("math");
$server->handle();
?>
Copy after login

Note:

a), math class is a webservice that will be made public;
b), $server->setClass, not $server->addClass.
2) Use PHP client to access the newly created SOAP service

< ? php
// $client = new SoapClient('http://localhost/php/soap/math.wsdl');
$client = new SoapClient("http://localhost/php/soap/soap_server.php?WSDL");
try{
  $result = $client->div(8, 2); // will cause a Soap Fault if divide by zero
  print "The answer is: $result";
}catch(SoapFault $e){
  print "Sorry an error was caught executing your request: {$e->getMessage()}";
}
?>
Copy after login

Essentially, http://localhost/php/soap/soap_server.php?WSDL is to be accessed The comment line refers to the wsdl description file, so this WSDL file must be generated in advance. For other languages ​​such as Java, it can be generated dynamically. For the SOAP extension that comes with PHP, this WSDL file must be generated in advance.

You can use ZendStudio to generate static WSDL files. At this time, the phpdoc of the math class is used as the metadata for generating WSDL. When using ZendStudio to generate wsdl files, the Web service target address must be correctly stated. The snippet is as follows:

...
  
    
      
    
  
...
Copy after login

   

注:调用PHP Webserver的方法必须传入命名参数。

更多PHP使用SOAP扩展实现WebService的方法相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!