Document directory
- Section 1. Overview
- Section 2. Soap
- Section 3. XML-RPC
Source: http://www.douzi.org/blog
Learning Materials: [wrox] professional open source web services
Chapter 8 PHP and Web Services
Download an English ebook [PDF]
The full text is divided into three parts:
- Overview.Advantages of Web Services Development in PHP: install and configure PHP on UNIX systems
- Use soap in PHP.Nusoap toolkit, nusoap's advanced Web service functions, such as HTTP proxy, soap over https, and document style messaging. We will also discuss how to solve some problems that may occur in PHP Web Services programming, such as security issues and ing between languages and data types.
- XML-RPC in PHP.XML-RPC features, XML-RPC vs soap, then use useful, Inc. Implementation to create XML-RPC client and server programs
The following is the first part.
Section 1. Overview
PHP has been bound to expat parser with built-in XML support. You can also use extension, such as domxml (DOM, XPath, xlink support), XSLT (outsourced programs for complex third-party XSLT libraries such as sablotron and libxslt ).
Another PHP extension useful for Web Service Development is curl (client URL library ). Curl allows you to communicate through different protocols, such as HTTP, https, FTP, telnet, and LDAP. HTTPS is particularly useful for secure connections between Web Services and servers.
Advantages and disadvantages of soap vs XML-RPC:
- Powerful Type Extension (SOAP)
- User-Defined character sets such as US-ASCII, UTF-8, UTF-16 (SOAP)
- Specifies recipient[Specify a container?](SOAP)
- The container fails when it encounters a message that cannot be understood (SOAP)
- Easy to use (XML-RPC)
- Simple Design (XML-RPC)
Configure PHP:
- Apache:To run php as an Apache module, use the -- with-apxs option for compilation, such as -- With-apxs =/www/bin/apxs. [I'm using apache2 now, and the option I'm compiling PHP is -- with-apxs2 =/usr/sbin/apxs]
- Domxml:Optional. It is very helpful for parsing XML documents. Libxml Library (version> = 2.4.2) needs to be installed in advance, and the -- with-dom = dir option is used during compilation (default DIR is/usr)
Http://www.xmlsoft.org/downloads.html
Libxml 2.6.4-sources-2.52 MB
- XSLT:Optional. It is helpful for converting XML data to other types of documents. Use the -- enable-XSLT -- With-XSLT-sablot option during compilation. The sablotron XSLT Library (http://www.gingerall.com/) must be installed in advance (the default DIR is/usr/lib or/usr/local/LIB ).
Sablotron 1.0.1-sources-470 KB
- Curl:As mentioned above, installation is required if SSL support is provided. Use the -- with-curl = dir option during compilation. You also need to install the curl Library (version> = 7.0.2-beta) in advance ). [My PHP has been installed. Curl information: libcurl/7.10.7 OpenSSL/0.9.7c zlib/1.1.4]
Continue yesterday's learning. Today, we mainly talk about nusoap.
Section 2. Introduction to soapnusoap:
Nusoap is an open-source PHP class used to send and receive soap messages through HTTP, developed by nusphere Corporation (http://www.nusphere.com
) Development. One advantage of nusoap is that it is not an extension, but written purely in PHP code, so it has a wide range of applicability.
Structure:
Installation Configuration:
Download from the http://dietrich.ganx4.com/nusoap/, extract the nusoap. php file from the ZIP file and put it in the include directory, add it in front of your script
Include ('nusoap. php ');
That's it.
Example:
The following is a simple soap client program: soap_client.php execution
// Simple client
Require ('nusoap. php ');
// Variable to be sent
$ Mystring = "world ";
// Parameters must be passed as an array
// The variable must be converted into an array.
$ Parameters = array ($ mystring );
// Create a soapclient object. The parameter is the URL of the server.
$ S = new soapclient ('HTTP: // www.douzi.org/me/php_ws/soap_server.php ');
// Call a remote method. The returned value is stored in $ result.
// The return value is a PHP variable type, such as string, integer, and array.
$ Result = $ S-> call ('echo string', $ parameters );
// Error Detection
If (! $ Err = $ S-> geterror ()){
Echo 'result: '. $ result; // success
} Else {
Echo 'error: '. $ err;
}
// Debugging. The following are the request and response packets, including the HTTP header.
Echo "<XMP>". $ S-> request. "</XMP> ";
Echo "<XMP>". $ S-> response. "</XMP> ";
?>
Corresponding server-side program: soap_server.php
// Simple Server
Require ('nusoap. php ');
// Create a new soap_server object and register a method that allows remote call.
$ S = new soap_server;
$ S-> Register ('echostring ');
$ S-> Register ('echoarray ');
/*
[The article said: without the registration step, any PHP function can be called remotely, which is a great security risk. However, I have tried to register. In addition, only the function that returns the result can be declared as a remote method. For example, echo () does not work, but strtolower () does.]
*/
Function echostring ($ inputstring ){
// Class check
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 be a string .');
// Soap_fault (faultcode, faultactor, faultstring, faultdetail );
// The above is the format of the constructor of the error handling class
// The value of faultcode is required. It can be set to client or server to indicate the end of the error.
// Faultactor is not implemented in nusoap.
// Faultstring error message.
// Faultdetail detailed error message. You can use XML tags.
// In addition to constructors, The soap_fault class also has a serialize () method.
// Serialize the error message and return a complete SOAP message. Example:
/*
$ Fault = new soap_fault ('client', '', 'the inputstring parameter must not be empty ');
Echo $ fault-> serialize ();
*/
}
}
// Demonstrate the use of array types
Function echoarray ($ inputstring ){
Return $ inputstring [0]. "+". $ inputstring [1];
}
// The last step is to pass all received post data to the service method of the soap server. It processes the request and calls the corresponding function.
$ S-> service ($ http_raw_post_data );
?>
Use of complex data types:
- Array.Part of the generated soap body code is as follows:
String1
String2
- Generate compound types samples and use soapval.Part of the generated soap body code is as follows:
123 freezing Lane
Nome
Alaska
12345 1234567890
0987654321
Example program: 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' => '000000', 'mobile' => '20140901 ')
);
$ S = new soapval ('myaddress', 'address', $ address, '', 'HTTP: // mynamespace.com ');
Print "<XMP>". $ S-> serialize (). "</XMP> ";
?>
WSDL
WSDLIs an XML language used to describe Web Services. It is a machine read format that provides all the information required to access the service to the Web service client. Nusoap provides a class to parse wdsl files and extract information from them. Soapclient objects use the WSDL class to make it easier for developers to call services. With the help of WSDL information, the programmer can call a message by knowing the operation name and parameters.
Using WSDL through nusoap provides the following advantages:
- All service meta files, such as namespaces, endpoint URLs, and parameter names, can be obtained directly from the WSDL file, this allows the client to dynamically adapt to changes on the server. Because the data can be obtained from the server at any time, you do not need to use hard encoding in the user script.
- It allows us to use the soap_proxy class. This class is derived from the soapclient class and adds the methods corresponding to the operations listed in the wdsl file. Now you can directly call these methods through it.
- The soapclient class contains a getproxy () method, which returns an object of the soap_proxy class. The soap_proxy class is derived from the soapclient class. It adds methods corresponding to the operations defined in the WSDL document and allows users to call an endpoint remote method. This is only applicable when the soapclient object is initialized using the wdsl file. The advantage is that it is easy for users to use. The disadvantage is that performance-creating objects in PHP is time-consuming and does not serve utilitarian purposes (and this functionality serves no utilitarian purpose ).
Example: WSDL. PHP Execution
// A simple WSDL demo File
Include ('nusoap. php ');
// The soap source provides a service for stars
// First, create a soapclient object and pass the URL of the WSDL file to the constructor,
// Use the second parameter to make the client know that the WSDL we passed is not the soap endpoint.
$ S = new soapclient ('HTTP: // www.abundanttech.com/webservices/deadoralive/deadoralive.wsdl', 'wsdl ');
// Generate proxy class
$ P = $ S-> getproxy ();
// Call a remote Function
$ Sq = $ p-> gettodaysbirthdays ();
If (! $ Err = $ p-> geterror ()){
Print_r ($ sq );
} Else {
Print "error: $ Err ";
}
Print 'request: <XMP> '. $ p-> request.' </XMP> ';
Print 'response: <XMP> '. str_replace ('> <', ">/n <", $ p-> response).' </XMP> ';
?>
Appendix: a useful web services demo site:
Http://www.mindreef.net/soapscope/wsdldemo
This is the last section. I think PHP is very suitable for clients. This section is mainly about XML-RPC.
I used to have a XML-RPC study note, which is similar to this.
Section 3. Data Type for the XML-RPCXML-RPC
XML-RPC supports only a limited number of data types. The following is the correspondence with the PHP Data Type:
Useful Inc. XML-RPC implementation -- phpxmlrpc
The XML-RPC toolkit we use is made by useful, Inc. EDD dumbill, which downloads the URL http://phpxmlrpc.sourceforge.net, which includes the complete XML-RPC Implementation of the client and server.
The client and server are implemented by the xmlrpc_client class and xmlrpc_server class respectively, and are mainly used to receive and send XML-RPC packets. The xmlrpcval class is used to encode PHP variables as XML-RPC equivalent data types and to pass parameters to remote methods. The opposite process uses the xmlrpc_decode () function. XML-RPC messages are created using the xmlrpcmsg class by passing it a parameter table.
The xmlrpc_client class sends XML-RPC messages created using the xmlrpcmsg class. on the server side, the xmlrpc_server class resolves these received packets as xmlrpcmsg objects. The object is then passed to the user function as a separate parameter. This function must return an xmlrpcresp object, which is used by the xmlrpc_server class for serialization and returned to the client. Shows the basic architecture.
Installation and configuration
Download, unpackage, and place XMLRPC. INC and xmlrpcs. Inc in your inclusion path in the http://phpxmlrpc.sourceforge.net.
Add the following statements to the client program header:
Include ('xmlrpc. inc ');
The following statement must be added to the header of the server program:
Include ('xmlrpc. inc ');
Include ('xmlrpcs. inc'); // server code
Example
XML-RPC client: xmlrpc_client.php execution
// Xmlrpc_client.php
// XML-RPC client demo
Require ('xmlrpc. inc ');
// Create a client object. The three parameters are path, hostname, and port.
$ S = new xmlrpc_client ('/XMLRPC/xmlrpc_server.php', 'www. windix. local', 80 );
// Create xmlrpcval object, which allows the encoding of our variable
// Create the xmlrpcval object and encode our PHP variables in the XML format required by the XML-RPC
$ Inputstring = new xmlrpcval ('World', 'string ');
// Create an array of parameters
// Although we only have one parameter, we still need to convert it into an array, because the second parameter of xmlrpcmsg is a parameter table.
$ Parameters = array ($ inputstring );
// Create the message object
// Create XML-RPC message, parameters are remote method name and parameter table
$ MSG = new xmlrpcmsg ('echo string', $ parameters );
// Send the message, get the response
// Send a message. The returned value $ RSp is an xmlrpcresp object. It contains the following three methods:
// Faultcode () error code. If the code is successful, 0 is returned.
// Faultstring () error message
// Value () return value, which exists in the form of xmlrpcval object. decoding is required 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
// Check the message content.
$ 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 demo
Require ('xmlrpc. inc ');
Require ('xmlrpcs. inc ');
// Service that echoes a string
// Custom functions used to process remote calls
// Note that this function must have only one parameter of the xmlrpcmsg object type
Function echostring ($ MSG ){
// Decode parameters into navtive types
// Use the xmlrpc_decode function for decoding.
$ Inputstring = xmlrpc_decode (array_shift ($ MSG-> Params ));
// Check for input parameter Validity
// Check whether the data type is correct
If (is_string ($ inputstring )){
Return new xmlrpcresp (New 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 function
// The following array is called "dispatch map". The item named "primary key" of the output function is an array.
// Contains the following three members:
// The Name Of The function actually called by the function. Here, our function name is also echostring, which is the same as the service name.
// Signature is optional. The type of input and output parameters. The last parameter is the output parameter. The previous parameter is the input parameter.
// Docstring is optional. Documents containing your services, or even HTML content.
// Xmlrpc_server also contains the second optional initialization parameter. If it is set to 0, the service will not process the request immediately.
// The process can be executed only when the service () method of the server is used
$ S = new xmlrpc_server (Array (
'Echo string' => array (
'Function' => 'echo string ',
'Signature' => array (Array ('string', 'string ')),
'Docstring' => 'This service echoes Hello + input stirng .'
)
));
?>