Home Backend Development PHP Tutorial PHP中XML-RPC使用详解

PHP中XML-RPC使用详解

Jun 20, 2016 pm 01:01 PM
php api

XML-RPC是Remote Procedure Call的缩写,翻译成中文就是远程过程调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算”,是为了提高各个分立机器的“互操作性”而发明出来的技术。

按照“数据即程序”的观点来看,RPC无非是借助一些通信手段来互相传递数据(信息),所也她也是“高”层次的通信手段,无非是这种通信手段看起来更像是“过程的调用”,因为她往往以一个“函数”的面目示人,从而掩盖了她交换信息的实质。
在各种RPC技术中,我想应该以Sun的RPC最为著名,比较流行的网络文件系统NFS就是建立在SUN RPC技术基础之上的。
XMLRPC,顾名思义(我总是喜欢这样把问题简单化,因为一个比较好的名字往往能概括出一个东西的本质,如果某个名字让你摸不着头脑,我推荐你放弃它,因为那个发明这个东西的人都不知道它的实质,所以你也就没有必要在其上浪费无谓的时间和精力。)就是应用了XML技术的RPC。那么什么是XML了?

XML和RPC一样也是一个东西的缩写,这个东西就是eXtensible Markup Language,中文意思就是可扩展标记语言,标记语言就是那种用尖括号()括来括去的那种语言,比如说HTML。XML 的可扩展性也体现在它只定义了语言的格式,而并没有定义过多的关键字,也就是通常所说的标记(Tag),所以用户可以自由地选择定义标记。它的这种自由和 简单的语法规则也使得它广为流传,被用来表示各种数据。熟悉Lisp语言(一种被称为“一大堆”括号的语言)的同学可能觉得XML和Lisp语言有些类 似,不同的是XML用尖括号替代了Lisp语言中的圆括号(())。事实就是他们都是那么相似,那么多语言似乎都是等价的,不同的只是那些应用语言的人。

XML在XMLRPC充当什么角色呢?

答 案就是“交换的数据格式”。在Sun RPC中,调用双方传递的数据是二进制的,而在XMLRPC中数据将是XML格式的。那么为什么用XML而不用二进制呢?我想一方面应该是为了兼容更多的 语言,因为这个世界上除了C/C++等编译语言,还有很多类似python,perl,javascrīpt等的脚本语言(最近有些文章也称其为“动态语 言”,因为他们通常不需要自己管理内存),另一方面是为了隔离操作系统的差异,比如说Little Endian和Big Endian的差异等。基于种种原因,XMLRPC选择了XML这种中间语言作为其信息的格式,然后由各个语言负责将其转变成各自native(本土)的 数据类型。关于为了兼容各个语言所发明的中间语言还有IDL(Interface Definition Language:接口定义语言),它被用于CORBA接口的定义。

关于XML-RPC的更多信息请到它的官方网站去学习,其中有XMLRPC的规范(Specification),不过是相当得简单的,因为XMLRPC本身就特别的简单,不相信?好,那下面我就请大家和我一起来学习如何写一个加法的XMLRPC。

服务器端:

因为XMLRPC的消息是用标准的HTTP协议进行传递的,所以我们的服务端也采用运行在apache上的php来开发,作为必要条件,我们需要在我们的系统上安装上php语言的xmlrpc开发库。我选用phpxmlrpc,因为php在很多情况下并不启用对XMLRPC的支持。

下载之后,将其的lib目录拷贝出来并命名为libphpxmlrpc,下面书写我们的第一个XMLRPC实现:
file: xmlrpc_server.php


include ("libphpxmlrpc/xmlrpc.inc");
include ("libphpxmlrpc/xmlrpcs.inc");

if ($_SERVER['REQUEST_METHOD'] != 'POST')
        exit(0);

$add_sig = array(array($xmlrpcString, $xmlrpcInt, $xmlrpcInt));
$add_doc = "Add the two integer together";

function add($params)
{
        global $xmlrpcerruser;

        $val = php_xmlrpc_decode($params);

        $ret = $val[0] + $val[1];

        return new xmlrpcresp(new xmlrpcval($ret, "int"));
}

$server = new xmlrpc_server(array(
        "add" => array(
                "function" => "add",
                "signature" => $add_sig,
                "docstring" => $add_doc
        )));

?>

 

是不是很简单明了啊?通过上面的代码我想您肯定可以通过CPCS(Copy, Paste, Change, Save)的方法举一反三出更多的XMLRPC来。

客户端:

为 了测试我们的程序是否正确,需要写一个客户端来,用什么来写呢?或者是用什么写更方便呢?简单思考之后,python应该比较简单,简单的google了 一下,得知xmlrpc的实现已经被纳入官方python的支持之中,窃喜,通过CPCS方法很快就写出了客户端实现,

如下:
File: xmlrpc_client.py

#!/bin/env python

from xmlrpclib import *
import sys

# xmlrpc add sample in python
server = Server("http://127.0.0.1/~xiaosuo/xmlrpc/xmlrpc_server.php");

try:
        retval = server.add(12, 13)
        print retval

except Error, v:
        print "Error", v

注:我开发的根目录为/home/xiaosuo/xmlrpc/所以网页的目录也就自然为http://127.0.0.1/~xiaosuo/xmlrpc/,以下相同。
测试:

xiaosuo@gentux xmlrpc $ ./xmlrpc_client.py
25

Ok!一切顺利。
以下还有几个语言的实现版本请看客们自行分析,并通过CPCS方法学习使用:
使用phpxmlrpc的php版:


include ("libphpxmlrpc/xmlrpc.inc");
include ("libphpxmlrpc/xmlrpcs.inc");

if (isset($_POST['var1']) && isset($_POST['var2'])) {
        $client = new xmlrpc_client("http://127.0.0.1/~xiaosuo/xmlrpc/xmlrpc_server.php");
        $msg = new xmlrpcmsg("add", array(
                new xmlrpcval($_POST['var1'], "int"),
                new xmlrpcval($_POST['var2'], "int")));
        $retval = &$client->send($msg);
        if ($retval->faultCode()) {
                print_r("An error occurred: ");
                print_r("Code: " . htmlspecialchars($retval->faultCode())
                        . " Reason: " . htmlspecialchars($retval->faultString()));
        } else {
                $sum = $retval->value()->scalarval();
        }
}

?>

br>                    "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-strict.dtd">


xmlrpc add sample in php


>
/>
+
/>

/>


使用来自xmlrpc-c的xmlrpc命令的shell版:

#!/bin/bash

xmlrpc http://127.0.0.1/~xiaosuo/xmlrpc/xmlrpc_server.php add i/12 i/13

使用xmlrpc-c的C语言版:


/*
 * Compile method:
 * gcc -o xmlrpc_client.out `xmlrpc-c-config --libs --cflags` xmlrpc_client.c -lxmlrpc_client
 */
#include
#include
#include
#include

#define NAME "XML-RPC C Test Client"
#define VERSION "1.0"

#define die_if_fault_occurred(x) /
        do { /
                if ((x)->fault_occurred) /
                abort(); /
        } while(0)

int main(int const argc, const char ** const argv)
{
        xmlrpc_env env;
        xmlrpc_value * resultP;
        int sum;
        char *const url = "http://127.0.0.1/~xiaosuo/xmlrpc/xmlrpc_server.php";
        char *const methodName = "add";

        /* Initialize our error-handling environment. */
        xmlrpc_env_init(&env);

        /* Start up our XML-RPC client library. */
        xmlrpc_client_init2(&env, XMLRPC_CLIENT_NO_FLAGS, NAME, VERSION, NULL, 0);
        die_if_fault_occurred(&env);

        /* Make the remote procedure call */
        resultP = xmlrpc_client_call(&env, url, methodName,
                        "(ii)", (xmlrpc_int32) 12, (xmlrpc_int32) 13);
        die_if_fault_occurred(&env);

        /* Get our state name and print it out. */
        xmlrpc_parse_value(&env, resultP, "i", &sum);
        die_if_fault_occurred(&env);
        printf("The sum  is %d/n", sum);

        /* Dispose of our result value. */
        xmlrpc_DECREF(resultP);

        /* Clean up our error-handling environment. */
        xmlrpc_env_clean(&env);

        /* Shutdown our XML-RPC client library. */
        xmlrpc_client_cleanup();

        return 0;
}

使用Frontier库的Perl版本:

#!/bin/env perl
#

use strict;
use warnings;
use Frontier::Client;

my $server = Frontier::Client->new(
        url => "http://127.0.0.1/~xiaosuo/xmlrpc/xmlrpc_server.php");

my $sum = $server->call("add", (12, 13));

print $sum . "/n";


是不是开始感叹XMLRPC被支持的程度了,事实上远不止这些,更多的语言支持请到XMLRPC的官方网站的实现列表里面去查看。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How API handles exception handling and retry mechanism in PHP How API handles exception handling and retry mechanism in PHP Jun 17, 2023 pm 03:52 PM

How APIs in PHP handle exception handling and retry mechanisms In PHP, APIs have become the core of many websites and applications as they provide various features and functions. However, when using APIs, we often encounter many problems, such as network connection problems, response timeouts, invalid requests, etc. In this case, we need to understand how to handle exceptions and retry mechanisms to ensure the reliability and stability of our applications. Exception handling In PHP, exception handling is a more elegant and readable error handling

PHP Kuaishou API Interface Development Guide: How to build a video download and upload system PHP Kuaishou API Interface Development Guide: How to build a video download and upload system Jul 22, 2023 am 11:13 AM

PHP Kuaishou API Interface Development Guide: How to Build a Video Download and Upload System Introduction: With the booming development of social media, more and more people like to share their life moments on the Internet. Among them, short video platforms continue to grow in popularity and have become an important way for people to record and share their lives and entertainment. The PHP Kuaishou API interface is a powerful tool that can help developers build feature-rich video download and upload systems. In this article, we will explore how to use the PHP Kuaishou API interface to develop a

How API handles caching and redundant data in PHP How API handles caching and redundant data in PHP Jun 17, 2023 pm 08:27 PM

PHP is a very popular server-side scripting language that is widely used in web development. In web development, API is a very important component, responsible for communicating with the client. Among them, API performance and efficiency are very important to the user experience of an application. Caching and redundant data are two important concepts during API development. This article will introduce how to handle them in PHP to improve the performance and reliability of the API. 1. Caching concept Caching is an optimization technology widely used in web applications.

How to collect and share videos through the PHP Kuaishou API interface How to collect and share videos through the PHP Kuaishou API interface Jul 21, 2023 pm 03:46 PM

Through the PHP Kuaishou API interface, video collection and sharing can be realized. In the era of mobile Internet, short videos have become an indispensable part of people's lives. As China’s mainstream short video social platform, Kuaishou has a huge user base. In order to improve user experience, we can implement video collection and sharing functions through the PHP Kuaishou API interface, allowing users to more conveniently manage and share their favorite videos. 1. Use Kuaishou API Kuaishou provides a rich API interface, including video search, video details, video collection and video analysis.

How to create a Twitter bot using PHP API How to create a Twitter bot using PHP API Jun 20, 2023 am 08:32 AM

With the popularity of social media, more and more people are beginning to use social media platforms such as Twitter for marketing and promotion. This approach is effective, but requires a lot of time and effort to stay active. If you want to promote your brand or service on Twitter but don’t have enough time or resources to manage an active Twitter account, then you might consider using a Twitter bot. A Twitter bot is an automated tool that helps you create your own posts on Twitter

How API handles multiple API clients in PHP How API handles multiple API clients in PHP Jun 17, 2023 pm 11:39 PM

In modern web applications, API interfaces are usually a way to implement service interfaces. When implementing such an API interface in PHP language, you need to consider how to handle multiple API clients. Under normal circumstances, each API client request will be processed through the RESTful interface implemented by PHP. However, when a large number of API client requests need to be handled, how to improve the interface processing efficiency and reduce system overhead has become an urgent problem to be solved.

PHP Kuaishou API Interface Development Guide: How to build a video playback and comment system PHP Kuaishou API Interface Development Guide: How to build a video playback and comment system Jul 21, 2023 pm 10:37 PM

PHP Kuaishou API Interface Development Guide: How to Build a Video Playback and Comment System Introduction: With the rise of the Kuaishou platform, many developers have developed various applications through its API interface. This article will introduce how to use PHP to develop the API interface of the Kuaishou video playback and comment system to help readers quickly get started and build their own applications. 1. Preparation work Before starting, you need to ensure that you have completed the following preparation work: Install PHP environment: You need to set up PH in the local development environment

Best Error Handling Practices for APIs in PHP Best Error Handling Practices for APIs in PHP Jun 17, 2023 am 10:37 AM

As a widely used programming language, PHP has become one of the main tools for web application development. When an application needs to interact with multiple external systems, such as databases, other web services, or third-party servers, using APIs is a popular implementation method. However, error handling is a very important part when writing APIs in PHP. Good error handling methods can not only continuously improve the reliability and robustness of the application, but also greatly improve the API usage experience. Here are some of the most

See all articles