Use SOAP in PHP

Source: Internet
Author: User
: This article mainly introduces the use of SOAP in PHP. if you are interested in the PHP Tutorial, refer to it. SOAP: SOAP. But it is this thing that has greatly affected the internet world. after a few years of speculation about the concept of "Web services", SOAP is its achievements or "heritage ", because SOAP is designed to implement 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 combination with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and multi-purpose Internet Mail Extension Protocol (MIME ). It also supports a large number of applications from the message system to remote process calling (RPC.
The Web service implemented through the SOAP protocol enables programmers all over the world to combine classes and functions to build a huge function library, which is language-independent. This depicts a bright development prospect for the software industry. as long as the network is connected together, code-level logical sharing can be realized, in the past, cross-process, cross-machine, and cross-network communication problems have all been solved, and the http protocol can cross the firewall (in fact, the firewall generally does not block port 80 of the http protocol, otherwise, no one will be connected to the Internet ).
It is no wonder that many people are very optimistic about this technology, saying it is "exciting ". Web services are easy to implement and can be simply released based on countless Web platforms on the Internet. Simple is often the most beautiful. Web services are a realistic example.
In PHP, after the php_soap.dll extension is enabled in the php. ini file, SOAP is supported.
There are three types of objects in the soap Extension Library.
1. SoapServer
It is used to define the functions that can be called and return response data when creating a php server page. The syntax format for creating a SoapServer object is as follows:
$ Soap = new SoapServer ($ wsdl, $ array );
$ Wsdl is the wsdl file used by shoap. wsdl is a standard format used to describe Web Service. if $ wsdl is set to null, the wsdl mode is not used. $ Array is the attributes of SoapServer and 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 );
$ Soap is a SoapServer object, and $ function_name is the name of the function to be called.
The handle method of the SoapServer object is used to process user input, call the corresponding function, and finally return the result to the client for processing. The syntax format is as follows:
$ Soap-> handle ([$ soap_request]);
$ Soap is a SoapServer object, and $ soap_request is an optional parameter to indicate the user's request information. If $ soap_request is not specified, the server will receive all user requests.
2. SoapCliet
This interface is used to call the SoapServer page on the remote server and call the corresponding function. The syntax format for creating a SoapClient object is as follows:
$ Soap = new SoapClient ($ wsdl, $ array );
The $ wsdl and $ array parameters are the same as those of SoapServer.
After creating a SoapClient object, calling the functions on the server page is equivalent to calling the SoapClient method. The Creation syntax is as follows:
$ Soap-> user_function ($ params );
$ Soap is a SoapClient object, user_function is the function to be called by the server, and $ params is the parameter to be passed in the function.
3. SoapFault
SoapFault is used to generate possible errors during soap access. The syntax format for creating a soapFault object is as follows:
$ Fault = new SoapFault ($ faultcode, $ faultstring );
$ Faultcode is the user-defined error code, and $ faultstring is the user-defined error message. The soapFault object is automatically generated when an error occurs on the server page or when you create a SoapFault object. For errors during Soap access, the client can capture the SoapFalut object to obtain the corresponding error information.
After capturing the SoapFault object on the client, you can use the following code to obtain the error code and error message:
$ Fault-> faultcode; // error code
$ Fault-> faultstring; // error message
$ Fault is the SoapFault object created earlier.
Example:
File soapfunc. php:
/* Several functions for the client to call */
Function reverse ($ str)
{
$ Retval = '';
If (strlen ($ str) <1)
{
Return new SoapFault ('client', '', 'invalidstring ');
}
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;
}
?>
File soapclsoapserverient. php content:
// Create a SoapServer object instance and register the function to be exposed,
// The Last handle () is used to process accepted soap requests.
Include_once ('soapfunc. php ');
Error_reporting (7); // set to 0 when officially released
Date_default_timezone_set ('prc'); // Set the time zone
$ 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 ();
?>
File soapclient. php content:
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 also implements Web service publishing through WSDL.

WSDL is a syntax specification used to describe Web services. for each Web service, it is a descriptive document that describes the location, protocol, and interface of web services in detail. provided by web service developers.

The WSDL file consists of five parts: types, Message, PortType, Binding, and Service.

1 Types definition: type definition, which is independent of the language and corresponds to the definition of element information to be transmitted in SOAP messages
2 Message: each web method corresponds to two message definitions: in and out. the message definition includes the header and body.
3 PortType: each web service corresponds to a PortType. this PortType also contains the release method, operation (operation)
4 Bindings: specify the binding information of each operation (class and method) in each porttype, including the format of the input and output messages.
5 Service: port information bound to each web service

In addition to publishing in the preceding example, Web services can also be published through the WSDL document.

Example:

Class to be released, 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 ();
?>

The WSDL description 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/">

























































Call 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 a WSDL document is troublesome and boring and error-prone. Many people think that things are not written by people. However, if there are good software tools, they do not need to be written. Zend's ZED 5.0 series and Zend Studio for eclipse 6.0 were originally well-supported for visual editing of WDSL and release of classes (intelligently generated according to a class file), but after Zend studio 7.0, this feature has been weakened. However, the Zend studio 7.xbuilt based on Eclipse still has a WSDL visual editor with sufficient functions. the generated WSDL file is slightly different from the previous one. Programmers must be familiar with the labels and elements in the WSDL document.

Appendix: PHP Soap development errors

1. during development, you must disable the php soap cache, which is required by both the server and client. Otherwise, the following message will be reported:

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: \ xampp \ htdocs \ clien. php (5): SoapClient-> test ()
#2 {main}

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

You can view Soap information by using methods such as $ client->__ getFunctions.


2. if the xml error is not identified during debugging, make sure that there is no irrelevant information such as spaces in the code, such as the BOM header of the Utf-8 encoding file.

Author: Zhang Qing (mesh) Xi'an PHP education training center
From mesh horizon: http://blog.why100000.com
Author Weibo: http://t.qq.com/zhangking
Why 100,000 computer learning networks: http://www.why100000.com


The above introduces the use of SOAP in PHP, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.