search
HomeBackend DevelopmentPHP TutorialPHP implements WebService through SOAP

PHP implements WebService through SOAP

Dec 29, 2017 pm 07:03 PM
phpsoapwebservice

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;
?>

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(); 
?>

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()}";
}
?>

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>
...

注:调用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
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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment