Подтвердить что ты не робот

Нужен образец кода клиента XML-RPC для PHP5

Требуется учебник или какая-либо инструкция по использованию библиотеки XML-RPC, встроенной в PHP (версия PHP версии 5.2.6) для клиента XML-RPC. Сервер находится в Python и работает.

Google и php.net терпят неудачу.

Обновление:

В phpinfo у меня установлен xmlrpc-epi v. 0.51. Я посетил http://xmlrpc-epi.sourceforge.net/, но в разделе примеров xmlrpc-epi-php слева показана версия sf.net версии 404.

Update2:

Я собираюсь использовать http://phpxmlrpc.sourceforge.net/ и, надеюсь, это сработает для меня.

Update3:

Код http://phpxmlrpc.sourceforge.net/ был прост, и я работал.

Не закрывать вопрос. Если кто-то хочет прослушивать ультра-простые решения, это будет здорово!

4b9b3361

Ответ 1

Очень простой клиент xmlrpc, я использую класс cURL, вы можете получить его из: https://github.com/dcai/curl/blob/master/src/dcai/curl.php

class xmlrpc_client {
    private $url;
    function __construct($url, $autoload=true) {
        $this->url = $url;
        $this->connection = new curl;
        $this->methods = array();
        if ($autoload) {
            $resp = $this->call('system.listMethods', null);
            $this->methods = $resp;
        }
    }
    public function call($method, $params = null) {
        $post = xmlrpc_encode_request($method, $params);
        return xmlrpc_decode($this->connection->post($this->url, $post));
    }
}
header('Content-Type: text/plain');
$rpc = "http://10.0.0.10/api.php";
$client = new xmlrpc_client($rpc, true);
$resp = $client->call('methodname', array());
print_r($resp);

Ответ 2

Ищете такое же решение. Это супер простой класс, который теоретически может работать с любым сервером XMLRPC. Я взбивал его через 20 минут, поэтому есть еще много желаний, таких как интроспекция, некоторые улучшения обработки ошибок и т.д.

file: xmlrpcclient.class.php

<?php

/**
 * XMLRPC Client
 *
 * Provides flexible API to interactive with XMLRPC service. This does _not_
 * restrict the developer in which calls it can send to the server. It also
 * provides no introspection (as of yet).
 *
 * Example Usage:
 *
 * include("xmlrpcclient.class.php");
 * $client = new XMLRPCClient("http://my.server.com/XMLRPC");
 * print var_export($client->myRpcMethod(0));
 * $client->close();
 *
 * Prints:
 * >>> array (
 * >>>   'message' => 'RPC method myRpcMethod invoked.',
 * >>>   'success' => true,
 * >>> )
 */

class XMLRPCClient
{
    public function __construct($uri)
    {
        $this->uri = $uri;
        $this->curl_hdl = null;
    }

    public function __destruct()
    {
        $this->close();
    }

    public function close()
    {
        if ($this->curl_hdl !== null)
        {
            curl_close($this->curl_hdl);
        }
        $this->curl_hdl = null;
    }

    public function setUri($uri)
    {
        $this->uri = $uri;
        $this->close();
    }

    public function __call($method, $params)
    {
        $xml = xmlrpc_encode_request($method, $params);

        if ($this->curl_hdl === null)
        {
            // Create cURL resource
            $this->curl_hdl = curl_init();

            // Configure options
            curl_setopt($this->curl_hdl, CURLOPT_URL, $this->uri);
            curl_setopt($this->curl_hdl, CURLOPT_HEADER, 0); 
            curl_setopt($this->curl_hdl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl_hdl, CURLOPT_POST, true);
        }

        curl_setopt($this->curl_hdl, CURLOPT_POSTFIELDS, $xml);

        // Invoke RPC command
        $response = curl_exec($this->curl_hdl);

        $result = xmlrpc_decode_request($response, $method);

        return $result;
    }
}

?>

Ответ 3

Я написал простую объектно-ориентированную оболочку, которая упрощает ее:

    require_once('ripcord.php');
    $client = ripcord::xmlrpcClient( $url );
    $score  = $client->method( $argument, $argument2, .. );

См. http://code.google.com/p/ripcord/wiki/RipcordClientManual для получения дополнительной информации и ссылку для загрузки.

Ответ 4

Я нашел это решение в http://code.runnable.com/UnEjkT04_CBwAAB4/how-to-create-a-xmlrpc-server-and-a-xmlrpc-client-for-php

Пример для входа в webfaction api

// login is the method in the xml-rpc server and username and password
// are the params
$request = xmlrpc_encode_request("login", array('username', 'password'));

$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));

$server = 'https://api.webfaction.com/'; // api url
$file = file_get_contents($server, false, $context);

$response = xmlrpc_decode($file);

print_r($response);

Вы увидите что-то вроде:

Array ( [0] => 5d354f42dcc5651fxe6d1a21b74cd [1] => Array ( [username] => yourusername [home] => /home [mail_server] => Mailbox14 [web_server] => Webxxx [id] => 123456 ) )

Ответ 5

Wordpress имеет XML-RPC.php файл, посмотрите на это.. он может помочь

Ответ 6

Кроме того, fxmlrpc (при использовании с NativeSerializer и NativeParser) представляет собой тонкую оболочку вокруг ext/xmlrpc.

Ответ 7

Из официальной ссылки php http://www.php.net/manual/en/ref.xmlrpc.php используйте пример степи (внизу) в качестве отправной точки. Он использует один и тот же сервер и легко настраивается. Это значит, что вы не хотите использовать внешнюю библиотеку или фреймворк. Но если вы это сделаете, посмотрите http://framework.zend.com/manual/1.12/en/zend.xmlrpc.server.html