Using XML technology to construct remote services in PHP

Source: Internet
Author: User
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 customer program in PHP through examples. I. service-oriented Web services from the simple method adopted by content providers to UDDI (UniversalDescription, Discoveryand future Web services will be service-centric Web, XML_RPC standard 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 customer program in PHP through examples.

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 http://www.xmlrpc.com/spec. 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"?>
<MethodCall>
<MethodName> examples. getStateName </methodName>
<Params>
<Param>
<Value> <i4> 41 </i4> </value>
</Param>
</Params>
</MethodCall>


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. Element description. Each Contains multiple , Each Contains And one . The following is a structure composed of two elements:

<Struct>
<Member>
<Name> name </name>
<Value> <string> member1 </string> </value>
</Member>
<Member>
<Name> member2 </name>
<Value> <i4> 19 </i4> </value>
</Member>
</Struct>


Can be nested, any Can contain Or any other type, including.

3.1.2 array

The value can be an array type, and the array is described as an element. Each element contains Element,The element can contain any number Element. The following is an example of an array element:

<Array>
<Data>
<Value> <boolean> 0 </boolean> </value>
<Value> <i4> 9 </i4> </value>
<Value> <string> Hello </string> </value>
</Data>
</Array>


The element has no name. As shown in values, the element values can be of various types. Element can be nested, any Can contain or other types, as described above .

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"?>
<MethodResponse>
<Params>
<Param>
<Value> <string> ABCDEFG </string> </value>
</Param>
</Params>
</MethodResponse>


May contain Structure, or may contain Structure, which is determined by whether the process call is successful. The structure is the same as that in XML requests, The element syntax is as follows:

<Fault>
<Value>
<Struct>
<Member>
<Name> faultCode </name>
<Value> <int> 4 </int> </value>
</Member>
<Member>
<Name> faultString </name>
<Value> <string> Error! </String> </value>
</Member>
</Struct>
</Value>
</Fault>

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 improves code reusability, but also brings a new distributed computing mode, in the next few years, it will surely 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 http://xmlrpc.usefulinc.com.

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", "betty.userland.com", 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", "luigi.melpomenia.com. 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, and the better interface for processing XML_RPC in programming languages. There are many reports on XML_RPC and service Web. let's keep a close eye on their development!


From: http://www.asfocus.com
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.