Using SOAP in PHP

WBOY
Release: 2016-07-30 13:29:27
Original
2003 people have browsed it

SOAP means "soap" in English. But this thing has influenced the Internet world to a great extent. After the concept of "Web services" was hyped in the past few years, SOAP is its achievement or "legacy", because SOAP ushered in the implementation of Web services.
SOAP = Simple Object Access Protocol, Simple Object Access Protocol. It is a lightweight, simple, XML-based protocol designed to exchange structured and solidified information on the WEB. SOAP can be used in conjunction with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Multipurpose Internet Mail Extensions (MIME). It also supports a wide range of applications from messaging systems to remote procedure calls (RPC).
Web services implemented through the SOAP protocol allow classes and functions written by programmers around the world to be gathered together to build a huge function library, which is language-independent. This depicts a brilliant development prospect for the software industry. As long as the network is connected, code-level logic sharing can be achieved. The past cross-process, cross-machine, and cross-network communication problems have all been solved, and http The protocol can pass through the firewall (in fact, firewalls generally do not block port 80 of the http protocol, otherwise no one will be able to access the Internet).
No wonder many people are very optimistic about this technology and call it "exciting".Web services are very simple to implement and can be easily published based on countless Web platforms on the Internet today. Simple is often the most beautiful, and Web services are a practical example.
In PHP, SOAP can be supported after the php_soap.dll extension is enabled in the php.ini file.
In the soap extension library, there are mainly three types of objects.
1. SoapServer
Used to define functions that can be called and return response data when creating php server-side pages. The syntax format for creating a SoapServer object is as follows:
  $soap = new SoapServer($wsdl, $array);
  Among them, $wsdl is the wsdl file used by shoep, wsdl is a standard format for describing Web Service, if $wsdl Set to null to not use wsdl mode. $array is the attribute information of SoapServer and is an array.
The addFunction method of the SoapServer object is used to declare which function can be called by the client. The syntax format is as follows:
$soap->addFunction($function_name);
Among them, $soap is a SoapServer object, and $function_name needs to be called. function name.
The handle method of the SoapServer object is used to process user input and call the corresponding function, and finally returns the processing result to the client. The syntax format is as follows:
$soap->handle([$soap_request]);
Among them, $soap is a SoapServer object, and $soap_request is an optional parameter used to represent the user's request information. If $soap_request is not specified, it means that the server will accept all requests from the user.
2. SoapCliet
is used to call the SoapServer page on the remote server and implements the call to the corresponding function. The syntax format for creating a SoapClient object is as follows:
$soap = new SoapClient($wsdl,$array);
Among them, the parameters $wsdl and $array are the same as SoapServer.
After creating the SoapClient object, calling the function in the server page is equivalent to calling the SoapClient method. The creation syntax is as follows:
$soap->user_function($params);
Among them, $soap is a SoapClient object and user_function is the server The function to be called, $params is the parameters to be passed into the function.
3. SoapFault
SoapFault is used to generate errors that may occur during soap access. The syntax format for creating a soapFault object is as follows:
$fault = new SoapFault($faultcode,$faultstring);
Among them, $faultcode is a user-defined error code, and $faultstring is a user-defined error message. The soapFault object is automatically generated when an error occurs on the server-side page, or when the user creates a SoapFault object. For errors that occur during Soap access, the client can obtain the corresponding error information by capturing the SoapFalut object.
After capturing the SoapFault object on the client, you can obtain the error code and error information through the following code:
$fault->faultcode;//Error code
$fault->faultstring;//Error information
Where, $fault Is the SoapFault object created earlier.
    示例:
    文件 soapfunc.php:
        /* 几个供client端调用的函数 */
    function reverse($str)
    {
      $retval='';
      if(strlen($str)<1)
      {
        return new SoapFault('Client','','Invalid string');
      }
      for($i=1; $i<=strlen($str); $i++)
      {
        $retval .= $str[(strlen($str)-$i)];
      }
      return $retval;
    }
    function add2numbers($num1, $num2)
    {
      if(trim($num1) != intval($num1))
      {
        return new SoapFault('Client','','The first number is invalid');
      }
      if(trim($num2) != intval($num2))
      {
        return new SoapFault('Client','','The second number is invalid');
      }
      return ($num1+$num2);
    }
    function gettime()
    {
      $time = date('Y-m-d H:i:s',time());
      return $time;
    }
    ?>
    文件 soapclsoapserverient.php 内容:
          //先创建一个SoapServer对象实例,然后将我们要暴露的函数注册,
      //最后的handle()用来处理接受的soap请求
      include_once('soapfunc.php');
      error_reporting(7); //正式发布时,设为 0
      date_default_timezone_set('PRC'); //设置时区
      $soap = new SoapServer(null, array('uri'=>"httr://test-rui"));
      $soap->addFunction('reverse');
      $soap->addFunction('add2numbers');
      $soap->addFunction('gettime');
      $soap->addFunction(SOAP_FUNCTIONS_ALL);
      $soap->handle();
    ?>
    文件 soapclient.php 内容:
          error_reporting(7);
      try
      {
        $client = new SoapClient(null, array('location'=>"http://localhost:8080/_myPHP5/soap/soapserver.php", 'uri'=>"http://test-uri"));
        $str="This string will be reversed";
        $reversed = $client->reverse($str);
        echo "if you reverse '$str', you will get '$reversed'";
        $n1 = 20;
        $n2 = 33;
        $sum = $client->add2numbers($n1,$n2);
        echo "
";
        echo "if you try $n1 + $n2, you will get $sum";
        echo "
";
        echo "The remoye system time is: ".$client->gettime();
      }
      catch(SoapFault $fault)
      {
        echo "Fault! code:" . $fault->faultcode . " string:" . $fault->faultstring;
      }
    ?>

PHP 中还实现了通过 WSDL 对 Web 服务的发布。

WSDL 是一种用于描述Web服务的语法规范,针对每个Web服务来说,它是一个说明文档,对web服务的位置,协议和接口进行详细的说明.由web服务的开发者提供。

WSDL文件包括5部分:types, Message,PortType,Binding和Service五部分.

1 Types definition: Type definition, independent of language. Corresponds to the definition of element information to be transmitted in the SOAP message
2 Message: Each web method corresponds to two message definitions in and out. The definition of message includes the header and body
3 PortType: Each web service corresponds to a PortType, which also contains the methods and operations published on it.
4 Bindings: Specifies the binding information of each operation (class and method) in each porttype, including The format of the input and output messages.
5 Service: The port information bound to each web service

In addition to publishing according to the aforementioned example, Web services can also be published through WSDL documents.

Example:

Class to publish, file myservice.php:
class service
{
public function HelloWorld()
{
return "Hello";
}
public function Add($a, $b)
{
return $a+$b;
}
}

$server=new SoapServer('TestSoap.wsdl',array('soap_version' => SOAP_1_2));
$server->setClass( "service");
$server->handle();
?>

WSDL description document, file TestSoap.wsdl:

targetNamespace="urn:TestSoap"
xmlns:typens="urn:TestSoap"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns :soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:wsdl="http:// schemas.xmlsoap.org/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/">












< /message>














































Calling code, file Client.php:

error_reporting(7);

$client = new SoapClient("http://localhost:8080/_myPHP5/soap/Wsdl/TestSoap.wsdl");
echo $client->HelloWorld() ;
echo("
");
echo $client->Add(10, 20);
?>

However, writing WSDL documents is a very troublesome thing, boring and error-prone . Many people think that this stuff was not written by humans, but if there are good software tools, then this stuff does not need to be written by humans. Zend's ZED 5.0 ​​series and Zend Studio for eclipse 6.0 originally supported WDSL visual editing and class publishing (intelligent generation according to a class file), but after Zend studio 7.0, this feature has been weakened. However, Zend studio 7.x, which is built on Eclipse, still has a WSDL visual editor, and its functions are sufficient. The generated WSDL The file has minor changes from before. Programmers must be familiar with the tags and elements in WSDL documents.

Appendix: Some errors about PHP soap development

1. When developing, be sure to turn off the cache of php soap, both the server and the client need it, otherwise it will report:

Fatal error: Uncaught SoapFault exception: [Client] Function ("test") is not a valid method for this service in ……clien.php:5 ​​Stack trace:
#0 [internal function]: SoapClient->__call('test', Array)
#1 D:xampphtdocsclien .php(5): SoapClient->test()
#2 {main}

Close method:
ini_set("soap.wsdl_cache_enabled", "0");

You can pass something like $client->__getFunctions( ) and other methods to view some information about Soap.


2. If an error of not recognizing XML is reported during debugging, please ensure that there are no spaces and other irrelevant information in the code, such as the BOM header of Utf-8 encoded files.

Author: Zhang Qing (Network) Xi'an PHP Education and Training Center 2010-7-11
From "Network Vision": http://blog.why100000.com
Author Weibo: http://t.qq.com/ zhangking
"One Hundred Thousand Whys" computer learning website: http://www.why100000.com


The above has introduced the use of SOAP in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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