PHP Invoke WebService Classic Instance

Source: Internet
Author: User
Tags php language soap md5 php class php code php tutorial web services wsdl

Nusoap is a WebService programming tool in the PHP environment for creating or invoking webservice. It is an open-source software that is a series of PHP classes written in PHP language and sent through HTTP to send and receive SOAP messages, developed by Nusphere Corporation (http://www.111cn.net/). One advantage of Nusoap is that there is no need to extend library support, which makes nusoap available to all PHP environments and is not affected by server security settings.

Method One: Direct call
?


Include (' nusoap.php tutorial ');

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

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

Calling remote functions
$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 Two: Proxy method call

?


Require (' nusoap.php ');

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

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

Calling remote functions
$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 invoke. NET WebService or Java EE WebService may have encountered Chinese garbled problems, the following describes the causes of the problem and the corresponding solutions.

Nusoap Call WebService the reason for garbled:

Usually we use the UTF-8 code for WebService development, when we need to set:

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

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

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

At this point should be all normal, but we are in the output of the results, but found that the return of garbled.

Nusoap Call WebService a garbled solution:

In fact, a friend who has turned on the debugging feature will find that $client->response is returning the correct result, why $result = $client->call ($action, Array (' Parameters ' => $ param)); But it's garbled?

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

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

Supplementary introduction

Nusoap is a Web services programming tool in the PHP environment that is used to create or invoke Web services. It is an open-source software, the current version is 0.7.2, supports SOAP1.1, WSDL1.1, and can interoperate with other systems that support SOAP1.1 and WSDL1.1. Nusoap is written entirely in PHP language and consists of a series of PHP classes that do not require support from the extension library, 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 based on the SourceForge, the network address is: http://sourceforge.net/projects/nusoap/, here, can download to the latest version of Nusoap.

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

2. Use of Nusoap
Nusoap is composed of a PHP class, where the most commonly used are class Soap_server and class Soalclient. Class Soap_server is used to create Web services that are used by class soapclient when accessing Web services.
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 this 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
<?php
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 a 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 Services 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 has been built, next, create a client program code file "/nusoap/nusoap_client1.php" to invoke the Web service:
Include the Nusoap source file in the current code file
<?php
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 '); A program that invokes a WEB service using the call method of the client object
$str = $client->call (' hello '); The GetError () method of the client object can be used to check whether an error occurred in the calling procedure.
If there are no errors, the GetError () method returns False, and 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);
}
?> so far, the client program is also set up, open the browser, access the client program, look at the results. In this example, the browser displays a string: "Program return: Hello world! ”
2.2 Methods for passing parameters and returning error messages
The method of passing the parameter and returning the error message is illustrated by an example. This example implements a two-string connection in which the argument is two strings, and the return value is a string connected by two parameters. First, create the service program code file "/nusoap/nusoap_server2.php", complete with the following code:
<?php
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 ', ", ' concatenate function argument should be two strings ');
}
$soap = new Soap_server;
$soap->register (' concatenate ');
$soap->service ($HTTP _raw_post_data);
The code structure here is roughly the same as the code comparison of the 2.1?> WEB service programs. Note the following two points:
The service program has a different definition, 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 of Nusoap is used here. When the incoming two arguments have one that is 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 server-side error.

Faultactor
Reserved items that are not currently used

FaultString
Description information for the error

Faultdetail
Optional, XML-formatted data, stating detailed error information

The complete contents of the client program code file "/nusoap/nusoap_client2.php" are as follows:
<?php
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 return:", $str;
} else {
echo "Error:", $err;
}
When a?> nusoap client invokes a WEB service with parameters, the array is used to pass parameters. The $parameters is an array, which in turn is the value of each parameter. When a client invokes a remote service program, it uses a call method with two arguments, the first parameter is the name of the service program, and the second parameter is an array of arguments to the service program, and here is the $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: $parameters =array ("string", 12), then access the client program through the browser, the browser will display a string: "Error: Client: The argument for the CONCATENATE function should be two strings ". The WEB service program determines that an incoming parameter is not a string and returns an error message to the client via Soap_fault.
2.3 Methods of debugging
There are three kinds of debugging methods commonly used in Nusoap:
Request and response member variables for the 2.3.1 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 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 to help you analyze how the program is running. Look at the following code:
<?php
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 return:", $str;
} else {
echo "Error:", $err;
}
The contents of the request and response variables are shown below
Echo ' <p/> ';
Echo ' Request: ';
Echo ' <pre> ', Htmlspecialchars ($client->request,ent_quotes), ' </pre> ';
Echo ' Response: ';
Echo ' <pre> ', Htmlspecialchars ($client->response,ent_quotes), ' </pre> ';
?>
DEBUG_STR member variables for 2.3.2 SoapClient class
The DEBUG_STR member variable of the SoapClient class provides more detailed debugging information, and viewing the contents of this variable can help you better debug your program.
2.3.3 The debugging method provided by the WEB service program
In the WEB Service program code, define the variable $debug = 1 before creating an instance of the Soap_server class. The debugging information, as a note, is placed at the end of the SOAP message to return the client and the client views the debugging information by viewing the response information of the WEB service.
<?php
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 ', ", ' concatenate function argument 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 class "WSDL". For nusoap users, it is not necessary to care about how the internal WSDL class works, and the proper use of the Soap_server class and the SoapClient class will enable the WSDL to be supported.
2.4.1 Create a WEB service that supports WSDL
In order to enable the Web service program to support WSDL, you need to use the Soap_server configurewsdl method, and you need to provide more detailed parameters when you call the Soap_server's Register method to register the Web service program. Look at the code below, the file name of the code is "/nusoap/nusoap_server3.php".
<?php
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 ', ", ' concatenate function argument should be two strings ');
}
$soap = new Soap_server;
$soap->configurewsdl (' concatenate '); Initializing support for WSDL
Registration Service
$soap->register (' concatenate ',
Array ("str1″=>" xsd:string "," str2″=> "xsd:string"),//input parameter definition
Array ("Return" => "xsd:string")//returns the definition of the parameter
);
$HTTP _raw_post_data = isset ($HTTP _raw_post_data)? $HTTP _raw_post_data: ";
$soap->service ($HTTP _raw_post_data);
?> now opens the browser, accesses the file just created, http://127.0.0.1/nusoap/nusoap_server3.php, the result is as follows:
Concatenate
View the WSDL for the service. Click on a operation name to view it's details.
Concatenate
Click the function name concatenate and you can see a description of the function. 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 invoke WEB services via WSDL
Invoking Web services through WSDL, the structure of the program is roughly the same as not invoking Web services through WSDL. The difference is that invoking the WEB service through WSDL, when initializing the SoapClient class, passes in two arguments to the SoapClient constructor, the first parameter is the address of the WSDL file, and the second parameter specifies whether to use the WSDL and specify True. Look at the code below, the file name of the code is "/nusoap/nusoap_client3.php"
<?php
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 return:", $str;
} else {
echo "Error:", $err;
}
Use of?> 2.4.3 Agent
Nusoap the method that provides the proxy to invoke the remote WEB service. This method creates a proxy object for a remote service in the client program, calls the remote WEB service directly through the proxy, and does not need to pass the call method of the Soalclient class. Look at the code below.
<?php
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″); Call a WEB service directly
if (! $err = $proxy->geterror ()) {
echo "program return:", $str;
} else {
echo "Error:", $err;
}
?>

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.