PHP 5 ExampleΒΆ

This is an example of how to use the Memset API with PHP 5 and the standard modules xmlrpc and curl.

Substitute API_KEY_HEX with a valid API key and it can be run with php-cli.

<?php
/*
 * Memset API example with PHP5.
 *
 * Requires PHP modules: xmlrpc and curl.
 */

// the API URL includes a valid API key
define('API_URL', 'https://API_KEY_HEX:@api.memset.com/v1/xmlrpc/');

// set to TRUE to get extra CURL info
define('DEBUG', FALSE);

// helper class, wraps xmlrpc and curl calls
class xmlrpc_cli {
        private $url;
        private $curl;

        function __construct($url) {
                $this->url = $url;
                $this->curl = curl_init();
        }

        function call($method, $params) {
                if ( $this->url == FALSE ) {
                        throw new Exception('Connection already closed');
                }

                $data = xmlrpc_encode_request($method, $params);
                if ( DEBUG ) {
                        curl_setopt($this->curl, CURLOPT_VERBOSE, TRUE);
                        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                }
                curl_setopt($this->curl, CURLOPT_URL, $this->url);
                curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($this->curl, CURLOPT_POST, 1);
                curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
                $result = curl_exec($this->curl);
                $errno = curl_errno($this->curl);
                if ( $errno || $result == FALSE ) {
                        throw new Exception("Method call failed:" .$result, $errno);
                }
                return xmlrpc_decode($result);
        }
        function close() {
                curl_close($this->curl);
                $this->url = FALSE;
        }
}

// MAIN

$client = new xmlrpc_cli(API_URL);

// get method list
$methods = $client->call('system.listMethods', array());
echo "Available methods:\n";
print_r($methods);

echo "The request failed:\n";
try {
        // API call fail will return a fault code
        $fail = $client->call('notfound', array());
        print_r($fail);
} catch (Exception $e)  {
        // the helper class will throw an exception when there's a
        // problem in the transport layer (HTTPS, ie. bad URL)
        print_r($e);
}

// example of method call with one parameter
$prod_info = $client->call('service.info', array(name=>'myserver'));
echo "Product info:\n";
print_r($prod_info);

$client->close();

Previous topic

Ruby Example

Next topic

node.js Example

This Page