PHP WebService instance Code call tutorial

Source: Internet
Author: User

Introduction: this is an example of WebService implementation in PHP.CodeOn the details page of the call tutorial, we will introduce PHP, related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 342055 'rolling = 'no'>

Nusoap is a WebService programming tool in the PHP environment. It is used to create or call WebService. It is an open-source software. It is a series of PHP classes written in PHP and used to send and receive soap messages over HTTP. It was developed by nusphere Corporation. One advantage of nusoap is that it does not require the support of extension libraries. This feature allows nusoap to be used in all PHP environments and is not affected by server security settings.

Method 1: directly call
<?

Include ('nusoap. php ');

// Create a soapclient object whose parameter is server's WSDL
$ Client = new soapclient ('HTTP: // localhost/WebServices/service. asmx? WSDL ', 'wsdl ');

// Input parameters in array format
$ Arypara = array ('strusername' => 'username', 'strpassword' => MD5 ('Password '));

// Call a remote Function
$ Aryresult = $ client-> call ('login', $ arypara );

// Echo $ client-> debug_str;
 

$ Document = $ client-> document;
Echo <soapdocument
<? XML version = "1.0" encoding = "gb2312"?>
<SOAP-ENV: Envelope
SOAP-ENV: encodingstyle = "http://schemas.xmlsoap.org/soap/encoding /"
Xmlns: SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope /"
Xmlns: XSD = "http://www.w3.org/2001/xmlschema"
Xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance"
Xmlns: SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding /"
Xmlns: SI = "http://soapinterop.org/xsd“>
SOAP-ENV: Body>
$ Document
SOAP-ENV: Body>
SOAP-ENV: envelope>
Soapdocument;

?>

Method 2: proxy call

<?

Require ('nusoap. php ');

// Create a soapclient object whose parameter is server's WSDL
$ Client = new soapclient ('HTTP: // localhost/WebServices/service. asmx? WSDL ', 'wsdl ');

// Generate proxy class
$ Proxy = $ client-> getproxy ();

// Call a remote Function
$ Aryresult = $ proxy-> login ('username', MD5 ('Password '));

// Echo $ client-> debug_str;
 

$ Document = $ proxy-> document;
Echo <soapdocument
<? XML version = "1.0" encoding = "gb2312"?>
<SOAP-ENV: Envelope
SOAP-ENV: encodingstyle = "http://schemas.xmlsoap.org/soap/encoding /"
Xmlns: SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope /"
Xmlns: XSD = "http://www.w3.org/2001/xmlschema"
Xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance"
Xmlns: SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding /"
Xmlns: SI = "http://soapinterop.org/xsd“>
SOAP-ENV: Body>
$ Document
SOAP-ENV: Body>
SOAP-ENV: envelope>
Soapdocument;

?>

Many friends who use nusoap to call. Net WebService or J2EE WebService may have encountered Chinese garbled characters. The following describes the causes and solutions of this problem.

Reasons for garbled WebService calling by nusoap:

Usually we do WebService development is used for UTF-8 encoding, then we need to set:

$ Client-> soap_defencoding = 'utf-8 ′;

At the same time, XML must be transmitted in the same encoding mode:

$ Client-> xml_encoding = 'utf-8 ′;

At this point, everything is normal, but when we output the results, we find that the returned code is garbled.

Solution to WebService call garbled by nusoap:

In fact, a friend who has enabled the debugging function will find that $ client-> response returns the correct result. Why is $ result =
$ Client-> call ($ action, array ('parameters '=> $ PARAM); is it garbled?

After studying the nusoap code, we will find that when xml_encoding is set to UTF-8, nusoap will detect the decode_utf8 setting. If it is true, it will execute the utf8_decode function in PHP, nusoap is set to true by default. Therefore, we need to set:

$ Client-> soap_defencoding = 'utf-8 ′;
$ Client-> decode_utf8 = false;
$ Client-> xml_encoding = 'utf-8 ′;

Additional information

Nusoap is a Web Service programming tool in the PHP environment. It is used to create or call Web Services. It is an open-source software. The current version is 0.7.2.
Soap1.1 and wsdl1.1 can interoperate with other systems that support soap1.1 and wsdl1.1. Nusoap
It is fully written by the PHP language and consists of a series of PHP classes without the support of extension libraries. This feature allows nusoap to be used for all PHP
Environment, not affected by server security settings.

1. obtain and install nusoap
The nusoap project is built on SourceForge and the network address is: http://sourceforge.net/projects/nusoap/, where you can download to the latest version of nusoap.

The installation of nusoap is relatively simple. Copying the downloaded nusoap file to the server can be stored in an independent directory orProgramPut the code in the same directory, as long as your PHP code can access these files.
The test environment in this article is based on php4.3.2 and nusoap 0.7.2. nusoap is installed in the web directory "/nusoap
There are two subdirectories: Lib and samples. The lib directory stores all nusoapSource codeFile, samples
The nusoap Development Team provides some examples in the directory. The test file is stored in the "/nusoap" web directory.

2. Use of nusoap
Nusoap is composed of PHP classes, the most common of which are soap_server classes and soalclient classes. The class soap_server is used to create Web Services, and the class soapclient is used to access web services.
2.1 A simple example: Hello World
This example uses nusoap to create a simple web service and
Create a client program and call this service. The only function of this service is to return a string "Hello World" to the client ". First, create a web
Service program code file "/nusoap/nusoap_server1.php ":
// Include the source file of nusoap into the current code file
<? PHP
Require_once ("lib/nusoap. php ");
// Define the Service Program
Function Hello (){
Return 'Hello world! ';
}
// Initialize the service object, which is an instance of the soap_server class
$ Soap = new soap_server; // call the Register Method of the service object to register the program to be accessed by the client.
// Only registered programs can be accessed by remote clients.
$ Soap-> Register ('hello'); // The last step is to pass the data submitted by the client in post mode to the service method of the service object.
// The service method processes the input data, calls the corresponding function or method, generates correct feedback, and returns it to the client.
$ Soap-> service ($ http_raw_post_data );
?> Now, the Web service program code file has been created. Next, create a client program code file "/nusoap/nusoap_client1.php" and call the Web Service:
// Include the source file of nusoap into the current code file
<? PHP
Require_once ("lib/nusoap. php ");
// Initialize the client object, which is an instance of soapclient class,
// Pass the URL of the service program to the constructor of the soapclient class.
$ Client = new soapclient ('HTTP: // www.3ppt.com/nusoap/nusoap_server1.php'); // use the call method of the client object to call the Web Service Program
$ STR = $ client-> call ('hello'); // The geterror () method of the client object can be used to check whether an error occurs during the call.
// If there is no error, the geterror () method returns false; if there is an error, the geterror () method returns an error message.
If (! $ Err = $ client-> geterror ()){
Echo "program return:", htmlentities ($ STR, ent_quotes );
} Else {
Echo "error:", htmlentities ($ err, ent_quotes );
}
?> Now, the client program has been established. Open the browser, access the client program, and check the result. In this example, the browser will display a string: "The program returns: Hello world! "
2.2 Methods for passing parameters and returning error messages
The example shows how to pass parameters and return error messages. In this example, two strings are connected. The parameters are two strings, and the returned values are strings connected by two parameters. First, create the service program code file "/nusoap/nusoap_server2.php". The complete code is as follows:
<? PHP
Require_once ("lib/nusoap. php ");
Function concatenate ($ str1, $ str2 ){
If (is_string ($ str1) & is_string ($ str2 ))
Return $ str1. $ str2;
Else
Return new soap_fault ('client', ", 'parameters of the concatenate function should be two string ');
}
$ Soap = new soap_server;
$ Soap-> Register ('concatenate ');
$ Soap-> service ($ http_raw_post_data );
?> Compared with the code of the web service program in section 2.1, the code structure here is roughly the same. Note the following:
Different service programs have two parameters. The process of registering a service program using nusoap is the same. The Register Method of the service object is called.
Here we use a new nusoap class soap_fault. When either of the two parameters is not a string, the program returns the error message to the client through this class. The constructor of this class has four parameters:
Fault
Code
Required parameter. The recommended value is "client" or "server", indicating whether the error is a client error or a server error.

Faultactor
Reserved item, not used yet

Faultstring
Error description

Faultdetail
Optional, XML format data, detailed error information

The complete content of the client code file "/nusoap/nusoap_client2.php" is as follows:
<? PHP
Require_once ("lib/nusoap. php ");
$ Client = new soapclient ('HTTP: // www.3ppt.com/nusoap/nusoap_server2.php ');
$ Parameters = array ('string 1', 'string 2 ′);
$ STR = $ client-> call ('concatenate', $ parameters );
If (! $ Err = $ client-> geterror ()){
Echo "program return:", $ STR;
} Else {
Echo "error:", $ err;
}
?> When a nusoap client calls a web service with parameters, it uses arrays to pass parameters. $ Parameters
Is an array with values of each parameter in sequence. When the client calls a remote service program, it uses a call with two parameters.
Method. The first parameter is the name of the Service Program, and the second parameter is the parameter array of the service program. Here is $ parameters.
. Access the client program in the browser, and the browser will display a string: "program return: String 1 string 2"
Next, try to pass in the error parameter to the Web Service Program, modify the above client program, and change the statement that generates the parameter array to: $ parameters = array ("String
", 12), and then access the client program through the browser, the browser will display the string:" error: Client: concatenate function parameter should be two strings ".
The Web Service Program judges that the input parameter is not a string and returns an error message to the client through soap_fault.
2.3 debugging method
There are three common debugging methods in nusoap:
2.3.1 request and response member variables of the soapclient class
The most direct debugging method is to check the request information sent by the client and the response information returned by the server during web service access.
Request and response of the soapclient class
The member variables contain the information, and the content of these two variables is displayed in the program, which can help analyze the running status of the program. See the following code:
<? PHP
Require_once ("lib/nusoap. php ");
$ Client = new soapclient ('HTTP: // www.3ppt.com/nusoap/nusoap_server2.php ');
$ Parameters = array ('string 1', 'string 2 ′);
$ STR = $ client-> call ('concatenate', $ parameters );
If (! $ Err = $ client-> geterror ()){
Echo "program return:", $ STR;
} Else {
Echo "error:", $ err;
}
// The content of the request and response variables is shown below
Echo '<p/> ';
Echo 'request :';
Echo '<PRE>', htmlspecialchars ($ client-> request, ent_quotes), '</PRE> ';
Echo 'response :';
Echo '<PRE>', htmlspecialchars ($ client-> response, ent_quotes), '</PRE> ';
?>
2.3.2 debug_str member variable of the soapclient class
The debug_str member variable of the soapclient class provides more detailed debugging information. You can view the content of this variable to better help program debugging.
2.3.3 debugging methods provided by web service programs
In the Web service program code, before creating an instance of the soap_server class, define the variable $ DEBUG = 1. The debugging information is used as a comment and is placed at the end of the SOAP message to return to the client. The client can view the debugging information by viewing the response information of the web service.
<? PHP
Require_once ("lib/nusoap. php ");
Function concatenate ($ str1, $ str2 ){
If (is_string ($ str1) & is_string ($ str2 ))
Return $ str1. $ str2;
Else
Return new soap_fault ('client', ", 'parameters of the concatenate function should be two string ');
}
$ DEBUG = 1; // define debugging
$ Soap = new soap_server;
$ Soap-> Register ('concatenate ');
$ Soap-> service ($ http_raw_post_data );
?> 2.4 support for WSDL
Nusoap supports WSDL through the "WSDL" class. For nusoap users, you do not need to worry about how the internal WSDL class works. You can use the soap_server class and soapclient class correctly to support the WSDL.
2.4.1 create a web service that supports WSDL
To support WSDL, The configurewsdl method of soap_server must be used and
The Register Method of soap_server must provide more detailed parameters when registering a web service program. See the following code. The code file name is
"/Nusoap/nusoap_server3.php ".
<? PHP
Require_once ("lib/nusoap. php ");
Function concatenate ($ str1, $ str2 ){
If (is_string ($ str1) & is_string ($ str2 ))
Return $ str1. $ str2;
Else
Return new soap_fault ('client', ", 'parameters of the concatenate function should be two string ');
}
$ Soap = new soap_server;
$ Soap-> configurewsdl ('concatenate'); // initialize the support for WSDL
// Register the service
$ Soap-> Register ('concatenate ',
Array ("str1" => "XSD: string", "str2" => "XSD: string"), // input parameter definition
Array ("return" => "XSD: string") // definition of the return Parameter
);
$ Http_raw_post_data = isset ($ http_raw_post_data )? $ Http_raw_post_data :";
$ Soap-> service ($ http_raw_post_data );
?> Open your browser and access the file you just created. The result is as follows: http://www.3ppt.com/nusoap/nusoap_server3.php:
Concatenate
View the WSDL for the service. Click on an operation name to view it's details.
Concatenate
Click the function name concatenate to view the function description. Click "WSDL" or access the Web service file and add the query string "? WSDL"
(Http://www.3ppt.com/nusoap/nusoap_server3.php? To obtain the WSDL content of the web service.
2.4.2 use WSDL to call Web Services
The structure of a program that calls a web service through WSDL is roughly the same as that of a Web service without using WSDL. The difference is that the Web
When initializing the soapclient class, two parameters are passed in to the soapclient constructor. The first parameter is the WSDL
File address. The second parameter specifies whether or not to use WSDL. Set this parameter to true. See the following code. The code file name is"
/Nusoap/nusoap_client3.php"
<? PHP
Require_once ("lib/nusoap. php ");
$ Client = new soapclient ('HTTP: // www.3ppt.com/nusoap/nusoap_server3.php? WSDL ', true );
$ Parameters = array ('string 1', 'string 2 ′);
$ STR = $ client-> call ('concatenate', $ parameters );
If (! $ Err = $ client-> geterror ()){
Echo "program return:", $ STR;
} Else {
Echo "error:", $ err;
}
?> 2.4.3 use of proxy
Nusoap provides proxy methods to call remote web services. In this way, create a remote service proxy object in the client program and call the remote web service directly through the proxy, instead of using the call method of the soalclient class. See the following code.
<? PHP
Require_once ("lib/nusoap. php ");
$ Client = new soapclient ('HTTP: // www.3ppt.com/nusoap/nusoap_server3.php? WSDL ', true );
$ Proxy = $ client-> getproxy (); // create a proxy object (soap_proxy class)
$ STR = $ proxy-> concatenate ("parameter 1", "parameter 2"); // directly call the Web Service
If (! $ Err = $ proxy-> geterror ()){
Echo "program return:", $ STR;
} Else {
Echo "error:", $ err;
}
?>

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/342055.html pageno: 6.

Related Article

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.