Using XML technology to construct remote services in PHP)

Source: Internet
Author: User
Tags php server

Introduction: This is a detailed page for constructing remote services (forwarding) using XML technology in PHP. It introduces PHP, related knowledge, skills, experience, and some PHP source code.

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

Using XML technology to construct remote services in PHP

In the future, the Web will be service-centered. xml_rpc makes writing and application services very simple. This article introduces the xml_rpc standard and its PHP implementation, and demonstrates how to develop the xml_rpc service and customerProgram.

I. Service web
From the simple method adopted by content providers to the future ideas of UDDI (Universal Description, discovery and integration), there have been a lot of comments on "Service web" in the industry. In the early stage of web development, it is just a distribution center for documents, providing only some information that can be browsed. With the development of Web, running services on the Web is becoming more and more attractive. In the future, Web will become a carrier for enterprises to provide convenient services for customers and other enterprises. The collaboration between B2B and B2C models can be seen as a service web.

A very important question is what services can be provided on the web? Web provides many services, some of which are currently in use, and some will appear in the near future. To illustrate the problem, a small part of the services that can be provided through the web are listed below:

A topic-oriented vertical search engine.
The knowledge base for users to find information.
You can consult an expert system.
Banking services.
News and information publishing services.
Digital payment-related services.
Graph processing service.
Health and health services.

So what is the correct way for enterprises and organizations to provide services through the web? This is a very important issue. Today, some services provide HTML interfaces. They provide services in the form of documents, but what is hidden behind the service interface? In the competition to occupy the Web, Web browsers are not alone. Mobile phones, handheld devices, and microwave devices all want to access the Web, query databases, convert data, and extract information. To implement a truly service-oriented web, there should be another layer under the presentation layer (HTML.

Ii. xml_rpc Standard
XML is perhaps the most important criterion in the past 10 years. The XML Vocabulary (Vocabulary) provides a cornerstone for enterprises to construct a service environment. To build a service web, it is necessary to learn the xml_rpc standard. This is not only because xml_rpc is useful for putting services on the web, but also because xml_rpc is a standard that has been formed and is easy to use. For B2B services, the standards for providing services are extremely important. companies that comply with the standards can use the services provided by other companies to achieve rapid growth. It cannot be imagined that a real service Web can be established based on various private service standards, and services must have a standard that can be followed.

Xml_rpc is a standard for Internet distributed processing. RPC is short for Remote Procedure Call. It is a remote call mechanism used to call processes that may reside on other machines and may be written in other languages. Remote Process calling is an important pillar of distributed computing. For example, in a distributed computing environment, we can find and use the process of performing addition and subtraction operations on other machines, the process of performing addition operations may be written in APL and run on rs6000 machines. The process of performing subtraction operations may be written in C and run on UNIX. Other developers who want to use this distributed calculator can also use them, or they can use another better calculator.

In RPC, the process (Procedure) is the most important component, and the server provides the process for the client to call. The process can receive parameters and return results. Xml_rpc uses HTTP as the Protocol carrier and implements the RPC mechanism through the XML vocabulary for sending and receiving data. The xml_rpc server receives the xml_rpc request and returns the xml_rpc response. The xml_rpc client program sends the xml_rpc request and receives the xml_rpc response. Servers and customers must handle responses and requests as required by the xml_rpc standard.

Iii. xml_rpc Protocol
The complete xml_rpc specification can be found at The following describes the key points.

3.1 xml_rpc request

The xml_rpc request should be an http post request whose body is in XML format. The XML format of the request is as follows:

<? XML version = "1.0"?>
<Methodname> examples. getstatename </methodname>
<Value> <I4> 41 </I4> </value>

The URL where the data is sent is not specified here. If the server is dedicated for RPC processing, it may be "/". The payload in the preceding XML document is a "methodcall" structure. Methodcall must contain a "methodname" sub-element. The "methodname" sub-element contains a string describing the method to be called. The Explanation of "methodname" is entirely determined by the server. For example, it can be the name of an execution file, the name recorded in the database, or anything else. If the process receives parameters, "methodcall" can contain one "Params" element and several "Param" sub-elements. Each "Param" element contains a value with a type descriptor, as shown in the following table:

Tag description
<I4> or <int> four-byte signed integer, such as 12
<Boolean> 0 (false), or 1 (true)
<String> string, such as "Hello World"
<Double> double-precision signed floating point number, such as-12.214
<Datetime. iso8601> date/time, for example, 19980717t14: 08: 55
<Base64> base64 encoded binary data, such as ew91igbid0ihjlqgdghpcye

3.1.1 Structure

The value can be a structure that is described by <struct>. Each <struct> contains multiple <member>, and each <member> contains one <Name> and one <value>. The following is a structure composed of two elements:

<Name> name </Name>
<Value> <string> member1 </string> </value>
<Name> member2 </Name>
<Value> <I4> 19 </I4> </value>

<Struct> can be nested. Any <value> can contain <struct> or any other types, including <array>.

3.1.2 Array

The value can be an array type, and the array is described using the <array> element. Each <array> element contains a <DATA> element, which can contain any number of <value> elements. The following is an example of an array element:

<Value> <Boolean> 0 </Boolean> </value>
<Value> <I4> 9 </I4> </value>
<Value> <string> Hello </string> </value>

<Array> the element has no name. As shown in struct, the <array> element value can be of various types. <Array> elements can be nested. Any <value> can contain <array> or other types, as described in <struct>.

3.2 xml_rpc response

The xml_rpc response is an HTTP response. The content type is text/XML. The format of the response body is as follows:

<? XML version = "1.0"?>
<Value> <string> abcdefg </string> </value>

<Methodresponse> may contain a <Params> structure or a <fault> structure, which is determined by whether the process call is successful. The <Params> structure is the same as that in the XML request. The syntax of the <fault> element is as follows:

<Name> faultcode </Name>
<Value> <int> 4 </int> </value>
<Name> faultstring </Name>
<Value> <string> error! </String> </value>

4. xml_rpc-based Web Services
Using xml_rpc to construct and use services is convenient. Enterprises deploy xml_rpc servers for their own services. Users, customer software, and customers can use these services to construct high-end services or end-user applications. This competition to provide more effective, inexpensive, and high-quality services will greatly improve the quality of application services.

However, there are still some problems to be solved, such as how to catalog, index, and search Web Services? UDDI tries to solve this problem, but this standard is not simple, and the industry's response to it is still unclear. However, the application of xml_rpc in an enterprise not only improvesCodeAnd will bring about a new distributed computing model. In the next few years, it will become an important intellectual wealth. The development of xml_rpc started from solving the distributed computing problem and becoming the basic layer of Service web, and thus gained a very good start. It will be followed by people's enthusiasm for this standard. Now, let's take a look at the actual application of xml_rpc!

4.1 apply xml_rpc in PHP

PHP is an ideal language for providing web services. We only need to write the PHP code, but place it in a proper place, and immediately have a service that can be called through the URL. Xml_rpc implementation in PHP may be complicated or simple, but we have many options. Here we use the xml_rpc implementation from useful information company. Its code and documentation can be downloaded from

The basic class implemented by xml_rpc involves two files:

XMLRPC. Inc: class required by the PHP client that contains xml_rpc

Xmlrpcs. Inc: class required by the PHP server that contains xml_rpc

4.2 Client

Compiling the xml_rpc client means:

1. Create an xml_rpc Request Message

2. Set the xml_rpc Parameter

3. Create an xml_rpc message

4. Send messages

5. Get a response

6. Explain the response

See the following example:

<? PHP
$ F = new xmlrpcmsg ('examples. getstatename ', array (New xmlrpcval (14, "int ")));
$ C = new xmlrpc_client ("/rpc2", "", 80 );
$ R = $ C-> send ($ F );
$ V = $ R-> value ();
If (! $ R-> faultcode ()){
Print "Status Code". $ http_post_vars ["stateno"]. "Yes ".
$ V-> scalarval (). "<br> ";
Print "<HR> This is the server response <br> <PRE> ".
Htmlentities ($ R-> serialize (). "</PRE> <HR> \ n ";
} Else {
Print "error :";
Print "Code:". $ R-> faultcode ().
"Cause: '". $ R-> faultstring (). "' <br> ";

In this example, we first create an xml_rpc message that calls the "examples. getstatename" method, and pass an integer parameter of the type "int" value of 14. Then, we created a customer that describes the URL to be called (path, domain, and port. Next, we sent the message, received the response object, and checked for errors. If no error exists, the result is displayed.

The main functions used to write RPC client programs are as follows:

Customer creation:

$ Client = new xmlrpc_client ($ server_path, $ server_hostname, $ server_port );

The message sending method is as follows:

$ Response = $ client-> send ($ xmlrpc_message );

It returns an instance of xmlrpcresp. The message we pass is an xmlrpcmsg instance, which is created using the following method:

$ MSG = new xmlrpcmsg ($ methodname, $ parameterarray );

Methodname is the name of the method (process) to be called, and parameterarray is the php array of the xmlrpcval object. For example:

$ MSG = new xmlrpcmsg ("examples. getstatename", array (New xmlrpcval (23, "int ")));

The xmlrpcval object can be created as follows:

<? PHP
$ Myval = new xmlrpcval ($ stringval );
$ Myval = new xmlrpcval ($ scalarval, "int" | "Boolean" | "string" | "double" | "datetime. iso8601" | "base64 ");
$ Myval = new xmlrpcval ($ arrayval, "array" | "struct ");

The first form creates the XMLRPC string value. The second form creates the descriptive value and type value. The third form creates complex objects by combining other XMLRPC values in arrays and other structures, such:

<? PHP
$ Myarray = new xmlrpcval (array (New xmlrpcval ("Tom"), new xmlrpcval ("dick"), new xmlrpcval ("Harry"), "array ");
$ Mystruct = new xmlrpcval (Array (
"Name" => New xmlrpcval ("Tom "),
"Age" => New xmlrpcval (34, "int "),
"Geek" => New xmlrpcval (1, "Boolean"), "struct ");

The response object is of the xmlrpcresp type and is obtained by calling the send method of the customer object. On the server side, we can create objects of the xmlrpcresp type as follows:

$ Resp = new xmlrpcresp ($ xmlrpcval );

On the client side, use the following method to obtain xmlrpcval from the response:

$ Xmlrpcval = $ resp-> value ();

Next, we can use the following method to obtain the PHP variable that describes the response result:

$ Scalarval = $ Val-> scalarval ();

Two functions are very useful for complex data types, both of which are in XMLRPC. Inc:

$ Arr = xmlrpc_decode ($ xmlrpc_val );

This function returns a PHP array containing the data in the xmlrpcval variable $ xmlrpc_val, which has been converted to the variable type of PHP.

$ Xmlrpc_val = xmlrpc_encode ($ phpval );

This function returns a value of the xmlrpcval type, which contains the PHP Data described by $ phpval. This method can perform Recursive Analysis on arrays and structures. Note that there is no support for non-basic data types (such as base-64 data or date-time data.

4.3 Server

Using the classes provided by xmlrpcs. Inc to write services is very simple. To create a service, create an xmlrpc_server instance as follows:

<? PHP
$ S = new xmlrpc_server (Array ("examples. myfunc" =>
Array ("function" => "foo ")));

The Consortium array passed to the xmlrpc_server constructor is a consortium array. The process "examples. myfunc" calls the "Foo" function. For this reason, foo is called a method handle.

Writing Method handles is simple. The following is the skeleton of a method handle:

<? PHP
Function Foo ($ Params ){
Global $ xmlrpcerruser; // introduce the user error code value
// $ Params is an array of xmlrpcval objects
If ($ ERR ){
// Error conditions
Return new xmlrpcresp (0, $ xmlrpcerruser + 1, // user error 1
"Error! ");
} Else {
// Succeeded
Return new xmlrpcresp (New xmlrpcval ("Fine! "," String "));

As you can see, the program has checked the error. If an error exists, an error is returned (starting from $ xmlrpcerruser + 1). Otherwise, xmlrpcresp indicating successful operations is returned if everything is normal.

V. Application Instances
In the following example, we construct a service. For the given value n, the service returns N * 2. The client uses this service to calculate the value of 5x2.

The server code is as follows:

<? PHP
Include ("XMLRPC. Inc ");
Include ("xmlrpcs. Inc ");
Function Foo ($ Params)
Global $ xmlrpcerruser; // introduce the user error code value
// $ Params is an array of the xmlrpcval object
$ Vala = $ Params-> Params [0];
$ Sval = $ Vala-> scalarval ();
$ Ret = $ sval * 2;
Return new xmlrpcresp (New xmlrpcval ($ ret, "int "));
$ S = new xmlrpc_server (Array ("product" =>
Array ("function" => "foo ")));

The client code is as follows:

<? PHP
Include ("XMLRPC. Inc ");
If ($ http_post_vars ["Number"]! = ""){
$ F = new xmlrpcmsg ('product', array (New xmlrpcval ($ http_post_vars ["Number"], "int ")));
$ C = new xmlrpc_client ("/XMLRPC/servfoo. php", " ar", 80 );
$ C-> setdebug (0 );
$ R = $ C-> send ($ F );
$ V = $ R-> value ();
If (! $ R-> faultcode ()){
Print "Number". $ http_post_vars ["Number"]. "is ".
$ V-> scalarval (). "<br> ";
Print "<HR> result from server! <Br> <PRE> ".
Htmlentities ($ R-> serialize (). "</PRE> <HR> \ n ";
} Else {
Print "operation failed :";
Print "Code:". $ R-> faultcode ().
"Cause: '". $ R-> faultstring (). "' <br> ";
Print "<form method = \" Post \ ">
<Input name = \ "number \" value = \ "$ {number} \">
<Input type = \ "Submit \" value = \ "Go \" name = \ "Submit \"> </form> <p>
Enter a value ";

Conclusion: the operation of the xml_rpc service also involves many other infrastructure and basic work, such as the cataloguing and indexing mechanism of distributed processes.Programming LanguageProcessing xml_rpc interfaces. There are many reports on xml_rpc and Service web. Let's keep a close eye on their development!

More articles on "using XML technology to construct remote services (transfer) in PHP"

Love J2EE follow Java Michael Jackson video station JSON online tools

Http:// pageno: 12.

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