The learning material is: [wrox]professional Open Source Web Services
Chapter 8 PHP and Web Services
English ebook download [PDF]
The full text is divided into three parts: a summary. PHP has the advantage of Web services development, installing configuration PHP on UNIX systems to use soap in PHP. NUSOAP Toolkit, Nusoap's advanced Web service features, such as HTTP proxy, SOAP over https,document style messaging. It will also discuss how to solve some of the problems that PHP WEB services programming will encounter, such as security issues, language-to-data-type mapping in PHP xml-rpc. XML-RPC features, xml-rpc vs. soap, and then use Useful, Inc. implementation to create XML-RPC client and server programs The following is the first part.
Section 1. The overview PHP has been bundled with expat parser built-in XML support, additional can also use some extensions (extension), such as Domxml (by using the Libxml Library to provide DOM, Xpath, XLink Support), XSLT ( Outsourced programs for complex third-party XSLT libraries, such as Sablotron and LIBXSLT.
Another PHP extension that is useful for web Service development is curl (Client URL Library). Curl allows you to communicate through different protocols, such as HTTP, HTTPS, FTP, Telnet, LDAP, where HTTPS is especially useful for Web services to secure connections to the server.
Soap vs XML-RPC Pros and cons: powerful type extension (SOAP) user-defined character set, such as Us-ascii, UTF-8, UTF-16 (SOAP) specifies recipient [Specify container?] (SOAP) container encounters an incomprehensible message fails (SOAP) easy to use (XML-RPC) design Simple (XML-RPC) configuration php:apache: for PHP to run as an Apache module, compile with the--WITH-APXS option, such as--wi Th-apxs=/www/bin/apxs. [I am now using the Apache2, I compiled PHP using the option is--WITH-APXS2=/USR/SBIN/APXS] Domxml: Optional features that are useful for parsing XML documents. Need to pre-install the Libxml library (version >=2.4.2), compile with the--with-dom=dir option (the default DIR is/usr)
Http://www.xmlsoft.org/downloads.html
Libxml 2.6.4-sources-2.52 MB
XSLT: An optional feature that is useful for converting XML data to other types of documents. Compile-time using the--ENABLE-XSLT--with-xslt-sablot option. The Sablotron XSLT library (http://www.gingerall.com/) must be pre-installed (the default dir is/usr/lib or/usr/local/lib).
Sablotron 1.0.1-sources-470 KB
CURL: As mentioned earlier, if SSL support is provided, it must be installed. Use the--with-curl=dir option at compile time. It is also necessary to pre-install the Curl Library (version >=7.0.2-beta). [My PHP is already installed.] CURL information:libcurl/7.10.7 openssl/0.9.7c zlib/1.1.4]
Go on with your study yesterday. Today is mainly about NUSOAP
Section 2. Soap Nusoap Description: Nusoap is a set of open-source PHP classes used to send and receive SOAP messages over HTTP, by Nusphere Corporation (http://www.nusphere.com/
Development One advantage of Nusoap is that he is not an extension, but is purely written in PHP code, so the scope of application is relatively wide.
Structure:
Installation configuration: Download from http://dietrich.ganx4.com/nusoap/, extract the nusoap.php file from the zip file to the Include directory, and precede your script with
Include (' nusoap.php ');
It's done.
Example: The following is a simple SOAP client program: soap_client.php execution
Simple Client
Require (' nusoap.php ');
The variable to send
$myString = "World";
Parameters must is passed as an array
Variables must be converted to the form of an array
$parameters =array ($myString);
Create a SoapClient object that is the URL of the server
$s =new soapclient (' http://www.douzi.org/me/php_ws/soap_server.php ');
Call the remote method, the return value is stored in the $result
A variable type that returns a value of PHP, such as String, Integer, array
$result = $s->call (' echostring ', $parameters);
Error detection
if (! $err = $s->geterror ()) {
Echo ' Result: '. $result; Success
} else {
Echo ' Error: '. $err;
}
Debug, the following is a message for the SOAP request and the response (response), including the HTTP header
echo "
". $s->request. " ";
echo " ". $s->response. " ";
?>
The appropriate server-side program: soap_server.php
Simple server
Require (' nusoap.php ');
Creates a new Soap_server object and registers a method that allows remote invocation
$s =new soap_server;
$s->register (' echostring ');
$s->register (' echoarray ');
/*
[The article said: missing the registration step, any PHP function will be able to make remote calls, which will be a great security risk. But I have tried to register is necessary. And only functions that return the result can be declared directly as a remote method, such as Echo (), and Strtolower (). ]
*/
function echostring ($inputString) {
Class checking
if (is_string ($inputString)) {
Return "Hello,". $inputString;
} else {
The Soap_fault class is used to generate error messages
return new Soap_fault (' Client ', ' ', ' the parameter to this service must is a string. ');
Soap_fault (FaultCode, Faultactor, faultstring, Faultdetail);
Above is the format of the constructor for the error handling class
FaultCode must be a value. Can be set to client or server to indicate which end the error occurred on.
Faultactor is not yet implemented in Nusoap.
FaultString error message.
Faultdetail detailed error information. You can use XML tags.
In addition to constructors, the Soap_fault class has a serialize () method
It serializes the error message and then returns a complete SOAP message, example:
/*
$fault = new Soap_fault (' Client ', ' ', ' the inputstring parameter must not be empty ');
echo $fault->serialize ();
*/
}
}
Demonstrating the use of array types
function Echoarray ($inputString) {
return $inputString [0]. " + ". $inputString [1];
}
The final step is to pass all the received post data to the service method of the SOAP server. It will process the request and invoke the appropriate function.
$s->service ($HTTP _raw_post_data);
?>
Use of complex data types: arrays. The following is the body part code of the generated soap:
String1
string2
Generates a composite data type (compound types samples), using Soapval. The following is the body part code of the generated soap:
123 Freezing Lane
Nome
Alaska
12345
1234567890
0987654321
Program Example: soapval.php execution
Soapval:general Compound Types Samples
Include (' nusoap.php ');
$address =array (
' Street ' = ' 123 freezing Lane ',
' City ' = ' Nome ',
' state ' = ' Alaska ',
' Zip ' =>12345,
' Phonenumbers ' =>array (' home ' = ' 1234567890 ', ' mobile ' = ' 0987654321 ')
);
$s =new soapval (' myAddress ', ' address ', $address, ' ', ' http://myNamespace.com ');
Print "
". $s->serialize (). " ";
?>
WSDL WSDL is an XML language used to describe a Web service. It is a machine-readable format that provides all the information necessary to access a service to a Web service client. Nusoap specializes in providing a class for parsing WDSL files and extracting information from them. The SoapClient object uses a WSDL class to alleviate the difficulty of the developer invoking the service. With the help of the WSDL information to create the message, the programmer simply needs to know the name and parameters of the operation to invoke it.
Using WSDL with NUSOAP provides the following advantages: All service meta-files, such as namespaces (namespaces), endpoint URLs, parameter names (parameter names), and so on, can be obtained directly from the WSDL file. This allows the client to dynamically adapt to server-side changes. Because it is readily available from the server, this data no longer requires hard coding in user scripts. It allows us to use the Soap_proxy class. This class derives from the SoapClient class and adds a method that corresponds to the operations detailed in the WDSL file. These methods can now be called directly by the user through it. The SoapClient class contains a GetProxy () method that returns an object of a Soap_proxy class. The Soap_proxy class derives from the SoapClient class, adding a method that corresponds to the operation defined in the WSDL document, and allows the user to invoke a endpoint remote method. This applies only to cases where the SoapClient object is initialized with the Wdsl file. The advantage is that it is easy for users to use, and the disadvantage is that creating objects in performance--php is time-consuming-and does not serve utilitarian purposes (and this functionality serves no utilitarian purpose).
Example: wsdl.php execution
A simple demo file for WSDL
Include (' nusoap.php ');
Soap source for a service that provides a star birth date
First we create a SoapClient object that passes the URL of the WSDL file to the constructor,
The second parameter is then used so that the client knows that we are passing the WSDL instead of the SOAP endpoint.
$s =new soapclient (' http://www.abundanttech.com/webservices/deadoralive/deadoralive.wsdl ', ' WSDL ');
Generate proxy class
$p = $s->getproxy ();
Calling a remote function
$SQ = $p->gettodaysbirthdays ();
if (! $err = $p->geterror ()) {
Print_r ($SQ);
} else {
Print "ERROR: $err";
}
print ' REQUEST:
'. $p->request. ' ';
print ' RESPONSE: '. Str_replace (' >< ', ">\n<", $p->response). ' ';
?>
Attached: a useful Web Services demo site: Http://www.mindreef.net/soapscope/wsdldemo
This is the last section, I feel PHP is still very suitable for the client. This section is mainly about XML-RPC.
I used to have a XML-RPC study note, which is similar to this one.
Section 3. XML-RPC data types for XML-RPC
XML-RPC only supports a limited number of data types. Here is the corresponding relationship to the PHP data type:
Useful Inc. XML-RPC implementation--PHPXMLRPC
The XML-RPC Toolkit We use is useful, Inc. 's Edd dumbill, download URL http://phpxmlrpc.sourceforge.net/, complete with the XML-RPC implementation of the client and server.
The client and server side are implemented by the Xmlrpc_client class and the Xmlrpc_server class, and are mainly used for receiving and sending XML-RPC messages. The Xmlrpcval class is used to encode PHP variables as XML-RPC equivalent data types and to pass parameters to remote methods. The opposite procedure uses the Xmlrpc_decode () function. The XML-RPC message is created using the Xmlrpcmsg class by passing it a parameter table.
The Xmlrpc_client class sends XML-RPC messages created using the Xmlrpcmsg class, and on the server side, the Xmlrpc_server class parses the received messages as xmlrpcmsg objects. The object is then passed as a single parameter to the user function. The function must return a Xmlrpcresp object that the Xmlrpc_server class uses to serialize and return to the client. This basic architecture is shown in.
Installation and Configuration
In http://phpxmlrpc.sourceforge.net/download, unpack, and then place Xmlrpc.inc and xmlrpcs.inc into your include path.
The client program header simply joins the following include statement:
Include (' Xmlrpc.inc ');
Server-side program header to add the following include statement:
Include (' Xmlrpc.inc ');
Include (' Xmlrpcs.inc '); Server-side code
Example
Xml-rpc client:xmlrpc_client.php Execution
xmlrpc_client.php
XML-RPC Client Demo Program
Require (' xmlrpc.inc ');
Create a client object, three parameters in turn path, hostname, port
$s =new xmlrpc_client ('/xmlrpc/xmlrpc_server.php ', ' www.windix.local ', 80);
Create Xmlrpcval object, which allows the encoding of our variable
Create a Xmlrpcval object and encode our PHP variable into the XML form required by XML-RPC
$inputString =new xmlrpcval (' World ', ' string ');
Create an array of parameters
Although we only have one parameter, we still want to convert the form of an array, because the second parameter of xmlrpcmsg is a parameter table
$parameters =array ($inputString);
Create the Message Object
Create XML-RPC messages with parameters for remote method names and parameter tables
$msg =new xmlrpcmsg (' echostring ', $parameters);
Send the message, get the response
Send message, return value $RSP is a Xmlrpcresp object, it contains the following three methods:
FaultCode () error code, if successful will return 0
FaultString () error message
Value () returns values as Xmlrpcval objects, which need to be decoded before PHP is used
$RSP = $s->send ($msg);
Check for errors
if ($rsp->faultcode () ==0) {
Decode the response to a PHP type
The Xmlrpc_decode () function is used to decode the Xmlrpcval object
$response =xmlrpc_decode ($RSP->value ());
Print results
print '
'
';
Var_dump ($response);
print ';
} else {
Print Errors
print ' Error: '. $RSP->faultcode (). ', '. $RSP->faultstring (). '
';
}
Show Messages
Then we'll look at the contents of the message.
$msg->createpayload ();
print ' REQUEST: <xmp> '. $msg->payload. ' </xmp> ';
print ' RESPONSE: <xmp> '. $RSP->serialize (). ' </xmp> ';
?>
Xml-rpc server:xmlrpc_server.php
xmlrpc_server.php
Xml-rpc Server-Side demo program
Require (' xmlrpc.inc ');
Require (' xmlrpcs.inc ');
Service that echoes a string
Our custom functions for handling remote calls
Note that the function must have only one parameter of type Xmlrpcmsg object
function echostring ($msg) {
Decode parameters into navtive types
First decode using the Xmlrpc_decode function
$inputString =xmlrpc_decode (Array_shift ($msg->params));
Check for input parameter validity
Check that the data type is correct
if (is_string ($inputString)) {
return new Xmlrpcresp (' Xmlrpcval (' Hello, '. $inputString, ' string '));
} else {//or return a fault
return new Xmlrpcresp (0, $xmlrpcerruser +1, "Parameter type". GetType ($inputString). "Mismatched expected type.");
}
}
Instantiate the server object and register our functions
Initialize the server object and register our functions
The following array is called "dispatch map", where an entry with the output function name as the primary key is an array
Consists of the following three members:
Function name actually called, here our function name is also echostring, the same as the service name
Signature is optional. The type of input and output parameters, the last one is the output parameter, the preceding is the input parameter
DocString is optional. Documents that contain your service, even HTML content.
The Xmlrpc_server also contains a second optional initialization parameter, and if set to 0, the service does not immediately process the request
Need to use server's service () method process to be executed
$s =new xmlrpc_server (Array (
' Echostring ' = Array (
' function ' = ' echostring ',
' signature ' = = Array (array (' String ', ' string ')),
' DocString ' = ' This service echoes Hello+input stirng. '
)
));
?>