Tuesday, January 30, 2007

PHP Arrays and XML-RPC

Are you frustrated by the XML-RPC technology?  Having trouble figuring how to get a hold of items after they have been transmitted over XML?  So was I.  Now I think I have figured it out.
Blog Ping

Let’s look first of all at a weblog update call using XMLRPC implementation by Keith Devens. You are going to send a ping to weblogs.com.

First, you start with an array:

$params = array(XMLRPC_prepare("my Blog"),XMLRPC_prepare("http://myblog.com/"));

Then you send it off.

$method = "weblogUpdates.ping";

$result = XMLRPC_request( "rpc.weblogs.com", "/RPC2", $method, $params );

When you pack it into the XML file it looks like this.

<?xml version="1.0" ?>

<methodCall>

    <methodName>examples.getStateName</methodName>

    <params>

      <param>

        <value>

          <string>My Blog</string>

        </value>

      </param>

      <param>

        <value>

          <string>http://myblog.com</string>

        </value>

      </param>

    </params>

</methodCall>

When you get it back from XML into PHP you will want to look at it in a PHP array. Suppose you get the parameters like this:

$xmlrpc_request = XMLRPC_parse($HTTP_RAW_POST_DATA);
$params = XMLRPC_getParams($xmlrpc_request);

Now you want to know how to get your three parameters. You do it like this:

$blogName = $params[0];

$blogURL = $params[1]

It’s that simple.

Blog Post

OK. Now let’s look at doing a blog post using the metaWebLog API. Now we have to put together a struct. What then?

A struct looks like this in PHP.

$struct = array (

’title’ => ’Blog Title’,

’description’ => ’Blog Post Content’);



When it gets to XML it looks something like this:

<?xml version="1.0" ?>

<methodCall>

  <methodName>metaWeblog.newPost</methodName>

  <params>

    <param>

      <value>

        <string>id</string>

      </value>

    </param>

    <param>

      <value>

        <string>user</string>

      </value>

    </param>

    <param>

      <value>

        <string>pass</string>

      </value>

    </param>

    <param>

      <value>

        <struct>

          <member>

            <name>description</name>

            <value>

              <string>Blog Post Content</string>

            </value>

          </member>

          <member>

            <name>title</name>

            <value>

              <string>Blog Title</string>

            </value>

          </member>

        </struct>

      </value>

    </param>

  </params>

</methodCall>

You then get it out of the XML file like this:

$xmlrpc_request = XMLRPC_parse($HTTP_RAW_POST_DATA);

$struct = XMLRPC_getParams($xmlrpc_request);


How to get the values? Like this:

$title = $struct[’title’];

$content = $struct[’description’];


And that’s it.

No comments:

Post a Comment