PHP Invoke WebService Instance Code _php tutorial

Source: Internet
Author: User
It is an open source software, developed by Nusphere Corporation (http://dietrich.ganx4.com/nusoap/), a series of PHP classes written entirely in PHP that send and receive SOAP messages over HTTP. One advantage of Nusoap is that there is no need for extended library support, which allows Nusoap to be used in all PHP environments and is not affected by server security settings.

Method One: Call directly
Copy CodeThe code is as follows:


Include (' nusoap.php ');

Creates a SoapClient object that is the WSDL of the server
$client = new SoapClient (' Http://localhost/Webservices/Service.asmx?WSDL ', ' WSDL ');

parameter to array form pass
$aryPara = Array (' strusername ' = ' username ', ' strpassword ' =>md5 (' password '));

Calling a remote function
$aryResult = $client->call (' login ', $aryPara);

Echo $client->debug_str;


$document = $client->document;
Echo <<


$document


Soapdocument;

?>

Method Two: Proxy mode invocation
Copy CodeThe code is as follows:


Require (' nusoap.php ');

Creates a SoapClient object that is the WSDL of the server
$client =new soapclient (' Http://localhost/Webservices/Service.asmx?WSDL ', ' WSDL ');

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

Calling a remote function
$aryResult = $proxy->login (' username ', MD5 (' password '));

Echo $client->debug_str;


$document = $proxy->document;
Echo <<


$document


Soapdocument;

?>

Many friends who use Nusoap to call. NET WebService or Java EE WebService may have encountered Chinese garbled problems, and the following describes the causes of this problem and the corresponding solutions.

Nusoap Call WebService garbled reason:

Usually when we do webservice development, we use UTF-8 encoding, which we need to set:

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

At the same time, the XML needs to be passed in the same encoding:

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

This should be all right, but when we output the results, but found that the return is garbled.

Nusoap Call WebService the solution that appears garbled:

In fact, the debugging function of the friend, I believe will find $client->response return is the correct result, why $result = $client->call ($action, Array (' Parameters ' = $ param)); But it's garbled?

After studying the NUSOAP code we will find that when xml_encoding is set to UTF-8, Nusoap detects the Decode_utf8 setting, and if true, executes the Utf8_decode function inside PHP, and Nusoap defaults to True , therefore, we need to set:

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

Supplemental information

Nusoap is a Web services programming tool for creating or invoking Web services in a PHP environment. It is an open source software, the current version is 0.7.2, supports SOAP1.1, WSDL1.1, can interoperate with other systems that support SOAP1.1 and WSDL1.1. Nusoap is written entirely in PHP and consists of a series of PHP classes that do not require extended library support, which makes nusoap available to all PHP environments and is not affected by server security settings.

1. Acquisition and installation of Nusoap
The Nusoap project is built on SourceForge, the network address is: http://sourceforge.net/projects/nusoap/, here, can be downloaded to the latest version of Nusoap.

Nusoap installation is relatively simple, the download of nusoap files copied to the server, can be placed in a separate directory, you can also be in the same directory with the program code, as long as your PHP code can access these files.
The test environment for this article is based on PHP4.3.2 and Nusoap 0.7.2, Nusoap installed in the WEB directory "/nusoap", with two subdirectories, Lib and samples. Where the Lib directory contains all the source code files of Nusoap, samples directory is the NUSOAP development team to provide some examples. The test file is stored in the WEB directory "/nusoap".

2. Use of Nusoap
Nusoap consists of a class of PHP, the most commonly used are class Soap_server and class Soalclient. Class Soap_server is used to create a Web service that is used by class soapclient when accessing a Web service.
2.1 A simple example: Hello world
This example will use Nusoap to create a simple WEB service and use Nusoap to create a client program that invokes the service. The only function of this service is to return a string "Hello world" to the client. First, create the WEB service program code file "/nusoap/nusoap_server1.php":
Include the Nusoap source file in the current code file.
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
Defining a service Program
function Hello () {
Return ' Hello world! ';
}
Initializes the service object, which is an instance of the class Soap_server
$soap = new Soap_server; The Register method that invokes the service object registers the program that needs 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 through post to the service method of the serving object.
The service method processes the input data, invokes the corresponding function or method, and generates the correct feedback, which is passed back to the client.
$soap->service ($HTTP _raw_post_data);
?>

Now that the Web service program code file is built, next, create a client program code file "/nusoap/nusoap_client1.php" that invokes the Web service:
Copy CodeThe code is as follows:
Include the Nusoap source file in the current code file.
Require_once ("lib/nusoap.php");
Initializes the client object, which is an instance of the class SoapClient,
Pass the URL address of the service program to the constructor of the SoapClient class.
$client = new SoapClient (' http://127.0.0.1/nusoap/nusoap_server1.php '); Invoking a program for a WEB service using the call method of a client object
$str = $client->call (' hello '); The GetError () method of the client object can be used to check for errors in the calling procedure.
If there is no error, the GetError () method returns False, and if there is an error, the GetError () method returns an error message.
if (! $err = $client->geterror ()) {
echo "program returns:", Htmlentities ($str, ent_quotes);
} else {
echo "Error:", Htmlentities ($err, ent_quotes);
}
?>

At this point, the client program is also set up, open the browser, access the client program, look at the results. In this example, the browser will display the string: "program return: Hello world! ”
2.2 Methods for passing parameters and returning error messages
The method of passing parameters and returning error information is illustrated by examples. This example implements the connection of two strings, the argument is two strings, and the return value is a string that is concatenated by two parameters. First, create the service program code file "/nusoap/nusoap_server2.php", the complete code is as follows:
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
function concatenate ($str 1, $str 2) {
if (is_string ($str 1) && is_string ($str 2))
Return $STR 1. $STR 2;
Else
return new Soap_fault (' Client ', ', ' The parameter of the ' concatenate ' function should be two strings ');
}
$soap = new Soap_server;
$soap->register (' concatenate ');
$soap->service ($HTTP _raw_post_data);
?>

Compared to the code in section 2.1 WEB service programs, the code structure here is roughly the same. Note the following two points:
The service program is defined differently, with two parameters. Nusoap the process of registering a service program is the same as the Register method that invokes the service object.
A new class Soap_fault for Nusoap is used here. When an incoming two parameter has a not a string, the program returns the error message to the client through this class. The constructor for this class has 4 parameters:
Fault
Code
Required parameter, the recommended value is "client" or "Server", indicating whether the error is a client error or a service-side error.

Faultactor
Reserved items that are not yet used

FaultString
Incorrect description information

Faultdetail
Optional, XML-formatted data that describes detailed error information

The complete contents of the client program code file "/nusoap/nusoap_client2.php" are as follows:
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
$client = new SoapClient (' http://127.0.0.1/nusoap/nusoap_server2.php ');
$parameters =array (' String 1′, ' string 2′);
$str = $client->call (' concatenate ', $parameters);
if (! $err = $client->geterror ()) {
echo "program returns:", $str;
} else {
echo "Error:", $err;
}
?>

When a NUSOAP client invokes a WEB service with parameters, it uses an array to pass the parameters. $parameters is an array in which the values of each parameter are sequentially. When a client invokes a remote service program, it uses a call method with two parameters, the first parameter is the name of the service program, and the second parameter is an array of parameters for the service program, here is $parameters. Through the browser to access the above client program, the browser will display a string: "program return: String 1 string 2"
Next, try to pass the error parameter to the WEB service program, modify the client program above, change the statement that generates the parameter array to: $parameters =array ("string", 12), and then through the browser to access the client program, the browser will display the string: "Error: Client: The parameters of the CONCATENATE function should be two strings ". The WEB service program determines that an incoming parameter has one that is not a string and returns an error message to the client through Soap_fault.
2.3 How to Debug
There are three types of debugging methods commonly used in Nusoap:
Request and response member variables of the 2.3.1 SoapClient class
The most straightforward debugging method is to check the request information sent by the client and the response information returned by the server in the process of accessing the WEB service. The request and response member variables of the SoapClient class contain this information, and the contents of the two variables are displayed in the program, which can help to analyze the situation in which the program is running. Look at the following code:
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
$client = new SoapClient (' http://127.0.0.1/nusoap/nusoap_server2.php ');
$parameters =array (' String 1′, ' string 2′);
$str = $client->call (' concatenate ', $parameters);
if (! $err = $client->geterror ()) {
echo "program returns:", $str;
} else {
echo "Error:", $err;
}
The contents of the request and response variables are shown below
Echo '

';
Echo ' Request: ';
Echo '
', Htmlspecialchars ($client->request,ent_quotes), '
';
Echo ' Response: ';
Echo '
', Htmlspecialchars ($client->response,ent_quotes), '
';
?>

2.3.2 DEBUG_STR member variables of the SoapClient class
The DEBUG_STR member variable of the SoapClient class provides more detailed debugging information, and viewing the contents of the variable can help debug the program better.
Debugging methods provided by the 2.3.3 WEB service Program
In the WEB Service program code, define the variable $debug = 1 before creating an instance of the Soap_server class. The debug information, as a comment, is returned to the client at the end of the SOAP message, and the client views the debug information by viewing the response information for the WEB service.
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
function concatenate ($str 1, $str 2) {
if (is_string ($str 1) && is_string ($str 2))
Return $STR 1. $STR 2;
Else
return new Soap_fault (' Client ', ', ' The parameter of the ' concatenate ' function should be two strings ');
}
$debug = 1; Defining debugging
$soap = new Soap_server;
$soap->register (' concatenate ');
$soap->service ($HTTP _raw_post_data);
?>

2.4 Support for WSDL
NUSOAP support for WSDL is implemented internally through the class "WSDL". For nusoap users, there is no need to be concerned about how the internal WSDL classes work, and the use of Soap_server classes and SoapClient classes to support WSDL can be implemented correctly.
2.4.1 Creating a WSDL-enabled WEB service
In order to implement a Web service program's support for WSDL, you need to use the Soap_server configurewsdl method, and you need to provide more detailed parameters when you register a Web service program by calling Soap_server's Register method. Look at the following code, the filename of the code is "/nusoap/nusoap_server3.php".
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
function concatenate ($str 1, $str 2) {
if (is_string ($str 1) && is_string ($str 2))
Return $STR 1. $STR 2;
Else
return new Soap_fault (' Client ', ', ' The parameter of the ' concatenate ' function should be two strings ');
}
$soap = new Soap_server;
$soap->configurewsdl (' concatenate '); Initializing support for WSDL
Registration Services
$soap->register (' concatenate ',
Array ("str1″=>" xsd:string "," str2″=> "xsd:string"),//definition of input parameters
Array ("return" = "xsd:string")//return parameter definition
);
$HTTP _raw_post_data = isset ($HTTP _raw_post_data)? $HTTP _raw_post_data: ";
$soap->service ($HTTP _raw_post_data);
?>

Now open the browser, access the file just created, http://127.0.0.1/nusoap/nusoap_server3.php, the results are as follows:
Concatenate
View the WSDL for the service. Click on a operation name to view it s details.
Concatenate
You can see the description of the function by clicking on the function name concatenate. You can get the WSDL content of the Web service by clicking "WSDL", or by accessing the Web service file, followed by the query string "? wsdl" (HTTP://127.0.0.1/NUSOAP/NUSOAP_SERVER3.PHP?WSDL).
2.4.2 calling WEB service via WSDL
Invoking a Web service through WSDL, and invoking a Web service without a WSDL, is roughly the same as the structure of the program. The difference is that when a WEB service is called through WSDL, the SoapClient class is initialized with two arguments to the SoapClient constructor, the first parameter is the address of the WSDL file, and the second parameter specifies whether to use WSDL, which is specified as true. Look at the following code, the filename of the code is "/nusoap/nusoap_client3.php"
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
$client = new SoapClient (' http://127.0.0.1/nusoap/nusoap_server3.php?wsdl ', true);
$parameters =array (' String 1′, ' string 2′);
$str = $client->call (' concatenate ', $parameters);
if (! $err = $client->geterror ()) {
echo "program returns:", $str;
} else {
echo "Error:", $err;
}
?>

Use of the 2.4.3 agent
Nusoap provides a proxy method to invoke a remote WEB service. This method creates a proxy object for the remote service inside the client program, invoking the remote WEB service directly through the proxy, without needing to pass the call method of the Soalclient class. Look at the code below.
Copy CodeThe code is as follows:
Require_once ("lib/nusoap.php");
$client = new SoapClient (' http://127.0.0.1/nusoap/nusoap_server3.php?wsdl ', true);
$proxy = $client-GetProxy (); Create proxy object (Soap_proxy Class)
$str = $proxy->concatenate ("parameter 1″," parameter 2″); Invoking a WEB service directly
if (! $err = $proxy->geterror ()) {
echo "program returns:", $str;
} else {
echo "Error:", $err;
}
?>

http://www.bkjia.com/PHPjc/324093.html www.bkjia.com true http://www.bkjia.com/PHPjc/324093.html techarticle It is an open source software, developed by Nusphere Corporation (http://dietrich.ganx4.com/nusoap/), a series of PHP classes written entirely in PHP that send and receive SOAP messages over HTTP. NuS ...

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