我花了一段时间才在没有外部库的情况下组装一个客户端。这组非常基本的客户端/服务器对在我的家庭设置中有效 - 希望它能为下一个 xml-rpc 新手省去一些麻烦。
/* clienttest.php */
<?php
function do_call($host, $port, $request) {
$fp = fsockopen($host, $port, $errno, $errstr);
$query = "POST /home/servertest.php HTTP/1.0\nUser_Agent: My Egg Client\nHost: ".$host."\nContent-Type: text/xml\nContent-Length: ".strlen($request)."\n\n".$request."\n";
if (!fputs($fp, $query, strlen($query))) {
$errstr = "Write error";
return 0;
}
$contents = '';
while (!feof($fp)) {
$contents .= fgets($fp);
}
fclose($fp);
return $contents;
}
$host = 'localhost';
$port = 80;
$request = xmlrpc_encode_request('cycle', 'egg');
$response = do_call($host, $port, $request);
?>
/* servertest.php */
<?php
function lifecycle($method, $params) {
switch($params[0]) {
case 'egg':
$reply = 'All eggs will be birds one day.';
break;
default:
$reply = 'That must have been an otheregg';
}
return $reply;
}
$server = xmlrpc_server_create();
xmlrpc_server_register_method($server, "cycle", "lifecycle");
$request = $HTTP_RAW_POST_DATA; $response = xmlrpc_server_call_method($server, $request, null);
header('Content-Type: text/xml');
print $response;
xmlrpc_server_destroy($server);
?>