Using XML technology to construct remote Service (RPM) in PHP

Source: Internet
Author: User
Tags date error code functions numeric value php code string version variable
xml| Remote service constructs remote service using XML technology in PHP

The future of the web will be a service-centric WEB,XML_RPC standard that makes authoring and application services very simple. This article describes the XML_RPC standard and its PHP implementation, and demonstrates how to develop XML_RPC services and client programs in PHP with examples.

A, service-type web
From the simple approach used by content providers to the future vision of UDDI (Universal description,discovery and integration), the industry already has a wealth of descriptions and comments about the "serviced Web". In the start-up phase of the Web, it is just a distribution center for a document, providing only some browsable information. With the development of the Web, running services on the web is becoming increasingly attractive. In the future, the web will become a carrier for customers and other enterprises to provide convenient services. Collaboration between Business-to-business and Business-to-consumer modes can be viewed as a service web.

A very important question is, what services can be provided on the Web? The web can provide a lot of services, some of which are already in use, and some services will be available in the near future. To illustrate the problem, a small subset of the services available through the Web are listed below:

A theme-oriented vertical search engine.
A knowledge base for users to find information.
A user can consult an expert system for questions.
Banking services.
News and information Publishing services.
Digital payment-related services.
Graphics processing services.
Health and health services.

So what is the right way for businesses and organizations to deliver services through the Web? This is a very important question. Today, some services provide HTML interfaces that provide services in the form of documents, but what is hidden behind the service interface? In the race to occupy the Web, Web browsers are not alone, and devices such as mobile phones, handheld devices and microwaves want to access the Web, query the database, transform data, extract information, and so on. There should be another layer under the presentation layer (HTML) to implement the True Service Web.

Second, XML_RPC standard
XML is perhaps the most important standard in nearly 10 years, and the XML Glossary (vocabulary) provides a cornerstone for the enterprise to construct a service environment. It is necessary to learn XML_RPC standards to build a serviced web, not only because XML_RPC is useful for putting services on the web, but because Xml_rpc is an already-formed, easily adopted standard. For business-to-business services, the standard of service delivery is extremely important, and companies that follow standards can use the services provided by other companies to achieve rapid growth. It is impossible to imagine that a true service Web can be built on top of a variety of proprietary service standards, and that services must have a standard to follow.

XML_RPC is a standard for internet-oriented distributed processing. RPC is the abbreviation for remote Procedure call (remote procedure invocation), which is a remoting mechanism for invoking procedures that may reside on other machines and may be written in other languages. Remote procedure call is an important pillar of distributed computing. For example, in a distributed computing environment, we can look for and utilize the process of performing addition and subtraction operations on other machines, the process of performing addition operations may be written in APL, run on RS6000 machines, and the process of performing subtraction 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 choose a better calculator.

In RPC, a procedure (Procedure) is the most important component, and the server provides a procedure for the client to invoke. Procedures can receive parameters and return results. XML_RPC uses HTTP as the protocol carrier to implement the RPC mechanism by sending and receiving the XML glossary of data. The XML_RPC server receives the XML_RPC request and returns the Xml_rpc answer, XML_RPC the client sends the XML_RPC request and receives the XML_RPC reply. The server and the customer must process the answers and requests as required by the XML_RPC standard.

Iii. XML_RPC Agreement
The complete XML_RPC specification can be found in Http://www.xmlrpc.com/spec. The following is a description of the key points.

3.1 XML_RPC Request

The XML_RPC request should be an HTTP POST request, and its body is in XML format. The XML part of the request is formatted as follows:

<?xml version= "1.0"? > >
<methodCall>
<methodName> Examples.getstatename </methodName>
<params>
<param>
<value> </value>
</param>
</params>
</methodCall>


The URL where the specified data is sent is not specified here. If the server is dedicated to RPC processing, it may be "/". The payload in the XML document described above is a "methodcall" structure. Methodcall must contain a "methodname" child element, and the "methodname" child element contains a string that describes the method to be called. How to interpret the content of "MethodName" is entirely up to the server, for example, it can be the name of an execution file, the name that is recorded in the database, or anything else. If the procedure receives parameters, "Methodcall" can contain a "params" element and several "param" child elements. Each "param" element contains a value with a type descriptor, and the type descriptor is shown in the following table:


Tag description
Or <int> four-byte signed integer, such as 12
<boolean> 0 (false), or 1 (true)
<string> string, such as "Hello World"
<double> Double signed floating-point numbers, such as-12.214
<dateTime.iso8601> Date/time, such as 19980717t14:08:55
<base64> base64 encoded binary data, such as Ew91igbid0ihjlqgdghpcye


3.1.1 Structure

The value can be a struct, and the structure is described with a <struct> element. Each <struct> contains multiple <member&gt, each <member> contains a <name> and a <value>. The following is a structure consisting of two elements:

<struct>
<member>
<name> name </name>
<value> <string> member1 </string> </value>
</member>
<member>
<name> Member2 </name>
<value> </value>
</member>
</struct>


<struct> can be nested, any <value> can include <struct> or any other type, including <array>.

3.1.2 Array

Values can be array types, and arrays are described with <array> elements. Each <array> element contains a <data> element,<data> element that can contain any number of <value> elements. The following is an example of an array element:

<array>
<data>
<value> <boolean> 0 </boolean> </value>
<value> 9 </value>
<value> <string> Hello </string> </value>
</data>
</array>


<array> element has no name. The value of the,<array> element, as shown in the preceding example, can be of various types. <array> elements can be nested, any <value> can contain <array> or other types, such as the <struct> described above.

3.2 Xml_rpc Answer

The Xml_rpc answer is an HTTP reply, and the content type is text/xml. The answer body is formatted as follows:

<?xml version= "1.0"? > >
<methodResponse>
<params>
<param>
<value> <string> ABCDEFG </string> </value>
</param>
</params>
</methodResponse>


<methodResponse> may contain a <params> structure, or it may contain a <fault> structure, depending on whether the procedure call succeeds. The syntax of the <params> structure is the same as the,<fault> element in an XML request:

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


Iv. Web services based on XML_RPC
It is convenient to use XML_RPC construction and service. Businesses deploy XML_RPC servers for the various services they provide, and users, customer software, and customer organizations can use this service to build high-end services or end-user applications. This competition, which provides more efficient, inexpensive and quality services, will greatly improve the quality of application services.

But there are still some problems to be solved, such as how to catalogue, index, search for services on the Web? UDDI is trying to solve this problem, but the standard is not simple, and the industry's response to it is not clear. However, the application of XML_RPC within the enterprise not only improves the reusability of the code, but also brings about a new distributed computing pattern, which will become an important intellectual asset in the years to come. The development of XML_RPC from solving the problem of distributed computing and becoming the basic level of the service web, thus getting a very good start, and then will be closely followed by people's enthusiasm for this standard. That being the case, let's take a look at the practical application of XML_RPC now!

4.1 Applying XML_RPC in PHP

PHP is an ideal language for providing Web services. We just write good PHP code but put it in a suitable location, immediately have a URL to "invoke" the service. XML_RPC implementations in PHP can be complex or simple, but we have many choices. Here we use the XML_RPC implementation from useful information company, whose code and documentation can be downloaded from http://xmlrpc.usefulinc.com/.

The basic class for this XML_RPC implementation involves two files:

Xmlrpc.inc: Classes required for PHP clients containing XML_RPC

Xmlrpcs.inc: Classes required to contain XML_RPC PHP servers

4.2 Client

Writing a XML_RPC client means:

1. Create a XML_RPC request message

2. Set XML_RPC parameters

3. Create a XML_RPC message

4. Send Message

5. Get a response

6. Explanation of Answer

Take a look at the following example:

<?php
$f =new xmlrpcmsg (' Examples.getstatename ', Array (new Xmlrpcval (), "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 answer to the server <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 a XML_RPC message that calls the "Examples.getstatename" method, and pass an integer parameter of type "int" with a value of 14. We then created a client that describes the URL to invoke (path, domain, and port). Next, we send a message, receive the answering object, and check for errors. If there is no error, we will display the result.

The main functions to use when writing RPC clients are as follows:

Create customer by:

$client =new xmlrpc_client ($server _path, $server _hostname, $server _port);

The way to send a message is:

$response = $client->send ($xmlrpc _message);

It returns an instance of the XMLRPCRESP. The message we pass is an instance of Xmlrpcmsg, which is created in the following way:

$msg =new xmlrpcmsg ($methodName, $parameterArray);

MethodName is the name of the method (procedure) to call, and Parameterarray is the Xmlrpcval object's PHP array. For example:

$msg =new xmlrpcmsg ("Examples.getstatename", Array (new Xmlrpcval (), "int"));

The Xmlrpcval object can be created in the following form:

<?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 a XMLRPC string value. The second form creates values that describe values and types. The third form creates complex objects by combining other XMLRPC values in structures such as arrays, for example:

<?php
$myArray =new Xmlrpcval (New Xmlrpcval ("Tom"), New Xmlrpcval ("Dick"), New Xmlrpcval ("Harry"), "array");
$myStruct =new xmlrpcval Array (
"Name" => new Xmlrpcval ("Tom"),
"Age" => new Xmlrpcval ("int"),
"Geek" => new Xmlrpcval (1, "Boolean")), "struct");
? >


The answer object is the Xmlrpcresp type, obtained by invoking the Send method of the client object. On the server side, we can create XMLRPCRESP types of objects in the following ways:

$resp =new Xmlrpcresp ($xmlrpcval);

On the client side, the following method is used to get xmlrpcval from the answer:

$xmlrpcVal = $resp->value ();

Next we can get a PHP variable that describes the answer in the following way:

$scalarVal = $val->scalarval ();

For complex data types, there are two functions that are useful, both of which are within Xmlrpc.inc:

$arr =xmlrpc_decode ($xmlrpc _val);

The function returns a PHP array that contains the data within the Xmlrpcval variable $xmlrpc_val, which has been converted to the variable type that PHP itself has.

$xmlrpc _val=xmlrpc_encode ($phpval);

This function returns a value of the Xmlrpcval type, which contains the PHP data described by $phpval. For arrays and structs, this method is capable of recursive analysis. Note that there is no support for non-basic data types such as base-64 data, or date-time data.

4.3 Server-side

Using the classes provided by Xmlrpcs.inc to write services is very simple. To create a service, we create an instance of Xmlrpc_server as follows:

<?php
$s =new xmlrpc_server (Array ("Examples.myfunc" =>
Array ("function" => "foo"));
? >

Passed to the Xmlrpc_server constructor is a federated array of a union array. The procedure "Examples.myfunc" invokes the "Foo" function, and for this reason Foo is called the method handle.

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

<?php
function foo ($params) {
Global $xmlrpcerruser; Introducing user error code values
$params is an array of Xmlrpcval objects
if ($err) {
Error condition
return new Xmlrpcresp (0, $xmlrpcerruser +1,//user error 1
"error!");
} else {
Success
return new Xmlrpcresp (New Xmlrpcval ("fine!", "string");
}
}
? >


As you can see, the program checks for errors and returns an error (starting from $xmlrpcerruser+1) if there are errors; otherwise, if everything works, return the XMLRPCRESP that describes the success information for the operation.

V. Examples of application
In the following example, we will construct a service. For the given number n, the service returns N*2. The client uses the service to compute the value of the 5*2.

The server-side code is as follows:

<?php
Include ("Xmlrpc.inc");
Include ("Xmlrpcs.inc");
function foo ($params)
{
Global $xmlrpcerruser; Introducing user error code values
$params is an array of Xmlrpcval objects
$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> results 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 numeric value ";
? >


Conclusion: The operation of XML_RPC services also involves many other infrastructure and infrastructure tasks, such as cataloging and indexing mechanisms for distributed processes, as well as processing XML_RPC better interfaces in programming languages. There are so many reports about XML_RPC and the service web, let's keep an eye on their development!

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.