Home Backend Development PHP Tutorial PHP implements WebService through SOAP

PHP implements WebService through SOAP

Dec 29, 2017 pm 07:03 PM
php soap webservice

This article mainly introduces the method of PHP using SOAP extension to implement WebService, and combines the examples with a more detailed analysis of the principles of SOAP extension and related techniques for implementing WebService. Friends in need can refer to it. I hope it will be helpful to everyone.

The details are as follows:

Recently, in a PHP project, connecting external interfaces involves WebService. There are not many related articles on search engines. Most of the ones I find refer to NuSOAP, a so-called powerful open source software. i.e. some classes. The environment in which the article is written and described is PHP 4.3. 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, I need to reference a lot of class files, so I still think it would be better to use the built-in SOAP extension added in PHP 5, as long as it can be practical. Let’s 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, Applied 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 incompatibilities 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

The 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 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 that accesses .NET WEB services:

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

4. Example

1) Use 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;
  }
  /**
  * p 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 p($a, $b){
    if($b == 0){
      throw new SoapFault(-1, "Cannot pide by zero!");
    }
    return $a / $b;
  }
}
$server = new SoapServer(&#39;math.wsdl&#39;, array(&#39;soap_version&#39;=>SOAP_1_2));
$server->setClass("math");
$server->handle(); 
?>
Copy after login

Note:

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

< ? php
// $client = new SoapClient(&#39;http://localhost/php/soap/math.wsdl&#39;);
$client = new SoapClient("http://localhost/php/soap/soap_server.php?WSDL");
try{
  $result = $client->p(8, 2); // will cause a Soap Fault if pide 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 access the wsdl pointed to by the comment line 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.

可以用ZendStudio生成静态的WSDL文件,此时用到math类的phpdoc作为生成WSDL的元数据。用ZendStudio生成wsdl文件时,必须正确说明Web服务目标地址,片断如下:

...
  <service name="mathService">
    <port binding="typens:mathBinding" name="mathPort">
      <soap:address location="http://localhost/php/soap/soap_server.php"></soap:address>
    </port>
  </service>
...
Copy after login

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

相关推荐:

如何使用php websocket创建简单聊天室

PHP Web实时消息后台服务器推送技术GoEasy

详谈PHP WEB服务器相关知识_PHP教程

The above is the detailed content of PHP implements WebService through SOAP. For more information, please follow other related articles on the PHP Chinese website!

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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles