PHPBuilder - Using XML: A PHP Developer's Primer, Part 4 Page 2 Page 2



RSS Twitter
Articles

Using XML: A PHP Developer's Primer, Part 4 Page 2 - Page 2

by: Adam Delves
|
August 7, 2008

The PHP application will take a username variable as input from the query string. The script will call two Flickr APIs. The first flickr.people.findByUsername, returns the unique user ID for the user given in the query string. The second API, flickr.people.getPublicPhotos, returns a list of public photos attached to the user ID.
Finding the User ID
A function wrapper is used to call the flickr.people.findByUsername and return the required data. To aid with readability, the wrapper function is given the same name as the API function that is being called.
  • The function first uses the arguments that are passed to it to set up the parameters which will be passed to the RPC message. An associative array is used to store each named argument expected by the API. When passed to an XML_RPC_Value object, an associative array is converted to an XML-RPC structure.

    new XML_RPC_Value($params'struct')

  • When initializing an XML_RPC_Value object, the second optional argument can be used to set the data type. If omitted, it defaults to a string.

  • The XML_RPC_Message object expects the name of the RPC and an array of XML_RPC_Value objects, which will be passed as parameters. When initializing an XML_RPC_Message object, the @ error suppression operator is used to prevent PHP from spitting out any notices.

    @(new XML_RPC_Message('flickr.people.findByUsername',
                                array(new 
    XML_RPC_Value($params'struct'))));

  • The send method of the XML_RPC_Client object sends the XML-RPC message to the server and returns the response. 
  • Upon receiving the response, the faultCode() method is called. A non-zero value indicates that a fault has occurred. If the RPC call fails, the fault description is loaded into the $error variable and a value of false is returned.

  • If the RPC call is successful, the return value (an XML document) is loaded into a Simple XML object and the value of the nsid attribute, as described in the API's documentation is returned.

PHP:

function 
flickr_people_findByUsername($username, &$error=false)
{
    
$apiKey $GLOBALS['apiKey']; // holds a reference to the RPC Client
    
$flickr $GLOBALS['flickr']; // an XML_RPC_Value object containing the API key

    
$params['api_key'] = $apiKey;
    
$params['username'] = new XML_RPC_Value($username);

    
/* create an RPC Message and initialize it with the parameters */
    
$flickr_people_findByUsername = @(new XML_RPC_Message('flickr.people.findByUsername',
                            array(new 
XML_RPC_Value($params'struct'))));

    
/* call the RPC */
    
$response $flickr->send($flickr_people_findByUsername);
    
    
/* check for a fault */
    
if (! $response->faultCode()) {
        
/* load the response into a Simple XML object */
        
$xml simplexml_load_string(XML_RPC_Decode($response->value()));
        
        return 
$xml['nsid']; // return the user ID
    
} else {
        
$error $response->faultString(); // set the $error variable to the fault description
        
return false;
    }
}

Returning a list of Photos


The flickr.people.getPublicPhotos function returns a list of photos in XML format. Each photo element has contains the information required to construct a URL to retrieve the image from the Flickr server.
  • Again, the wrapper function uses the arguments passed to construct an associative array of arguments to pass to the RPC function.
  • A SimpleXMLElment object is used again to represent the data returned in the response.
  • If no photos are returned, the function returns false.
  • If one or more photos were found, the function returns the list of photos as a SimpleXMLElement object.

    return $xml->photo// return only the photo list

PHP:

function 
flickr_people_getPublicPhotos($user_id$per_page=null$page_no=null$extras=null, &$error=false)
{
    
$apiKey $GLOBALS['apiKey']; // holds a reference to the RPC Client
    
$flickr $GLOBALS['flickr']; // an XML_RPC_Value object containing the API key
    
    
$params['api_key'] = $apiKey;

    
$params['user_id'] = new XML_RPC_Value($user_id);
    
    
/* load optional arguments where they have been supplied */
    
if (! is_null($per_page)) {
        
$params['per_page'] = new XML_RPC_Value($per_page);
    }

    if (! 
is_null($page_no)) {
        
$params['page_no'] = new XML_RPC_Value($page_no);
    }

    if (! 
is_null($extras)) {
        
$params['extras'] = new XML_RPC_Value($extras);
    }    
    
    
/* create an RPC Message and initialize it with the parameters */
    
$flickr_people_getPublicPhotos = @(new XML_RPC_Message('flickr.people.getPublicPhotos',
                                array(new 
XML_RPC_Value($params'struct'))));        
    
    
/* call the RPC */
    
$response $flickr->send($flickr_people_getPublicPhotos);

    if (! 
$response->faultCode()) {
        
/* if the response is alid, load it into a SimpleXMLElement and return */
        
$xml simplexml_load_string(XML_RPC_Decode($response->value()));
    } else {
       
$error $response->faultString();
       return 
false;
    }    

    if (
$xml['total'] == 0) {
        
/* if not photos were found, return an error */
        
$error 'No Photos';
        return 
false;
    } else {
        return 
$xml->photo// return only the photo list
    
}
}
Displaying the Pictures
The main part of the script does the following:
  • Checks for the username variable in the query string.
  • Creates a global instance of an XML_RPC_Client object, which the two wrapper functions will user.
  • Creates a global instance of an XML_RPC_Value object, containing the API key, require by all Flickr API's.
  • Calls the two wrapper functions.
  • Displays an error, or the returned images by traversing through the photo elements in the SimpleXMLElement object.

PHP:

    $error false;
    
$apiKey = new XML_RPC_Value('[ENTER API KEY HERE]');
   
    
/* check first for a user name sent with the query string - if this does not exist an error is returned */
    
if (isset($_GET['username'])) {
   
    /* create the client - the URI of the server endpoint and the host are both required */
        
$flickr = new XML_RPC_Client('/services/xmlrpc/''www.flickr.com');
    
       
/* find the user_id */
        
$username $_GET['username'];
    
        
/* only get the pictures if the request for the user ID succeeded */
       
if (($user_id flickr_people_findByUsername($username$error))) {
            
$photos flickr_people_getPublicPhotos($user_id41null$error);   
        }    
    } else {
        
$error ='No Username Specified';
    }
Modifying the Email Validator
The real power of RPC can only be appreciated when it is used to bridge the gap between two different programming languages. The next example is going to convert the Ajax Email Validation application, as seen in the second article in this series, to call the RPCs exposed by a server endpoint written in PHP. The email validation application shows how Ajax can be used to validate an email address without submitting the form. The validator contains an Ajax engine which communicates with a back-end script.

The back-end script will now act as a RPC server and map several functions of the EmailValidator object to RPC. The Ajax engine will no longer be an Ajax engine (the Javascript RPC client will handle this); instead it will call the RPC functions that reside on the PHP server.

Before continuing, you'll need download the ZIP file that accompanies this article. As well as all the source code examples given here, it also contains additional components which will be used in this application:
  • emailValidator.php – This contains an Email Validation class that uses an SQLLite database to store verified email addresses and provides the methods necessary to check the email address syntax and verify the verification code.
  • ajrpc.js – This contains an XML-RPC client for Javascript. The AJ-RPC client uses the XMLHTTPRequest to send and receive the XML-RPC payloads and allows method RPC calls to be made both synchronously and asynchronously.

Continued Next Week!

Join us next week as we finish up Part 5 and discuss the creation of the PHP RPC server and interface!!



« Previous Page
1

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Adam Delves

Comment:



Comment:

(Maximum characters: 1200). You have characters left.