ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

PHP Amazon Web Services Class

This class, written by Dennis Pallett, is used to query Amazon Web Services (a developers’ token is required), and retrieve results from Amazon. The class includes automatic caching for increased stability and speed of your website.

###################################################################################
#
# AWS Class, by Dennis Pallett, version 0.1
# http://www.nocertainty.com/e/aws-class
#
# Modified version of XML Library, by Keith Devens included
# See http://keithdevens.com/software/phpxml for a regular version
#
# This code is Open Source, released under terms similar to the Artistic License.
# Read the license at http://keithdevens.com/software/license
###################################################################################

class AWS {
    var 
$parser;   #a reference to the XML parser
    
var $document#the entire XML structure built up so far
    
var $parent;   #a pointer to the current parent - the parent will be an array
    
var $stack;    #a stack of the most recent parent at each nesting level
    
var $last_opened_tag#keeps track of the last tag opened.
    
var $token# AWS Developer Token
    
var $associateid# Amazon Associate ID
    
var $directory# Directory where all cached XML files should be stored
    
var $error# Contains error messages, if any

    // Constructor:
    
function AWS($Token$AssociateID="aspit-20"){
        
$this->token $Token;
        
$this->associateid $AssociateID;
    }

    function 
go ($url) {
        
// Insert associate id and dev token in string
        
$url str_replace("[devtoken]"$this->token$url);
        
$url str_replace ("[associateid]"$this->associateid$url);


        
// Create cached filename
        
$cachefn md5($url);
        
$cachefn .= ".xml";
        
$cachefn $this->directory $cachefn;

        
// Does a cached file exist?
        
if (file_exists ($cachefn)) {
            
// Get last modified time
            
$cachetime filemtime($cachefn);

            
// Cache too old?
            
if ($cachetime mktime() - 60*60*24) {
                
// Get xml from local cache
                
$xml implode(" "file($cachefn));
            }
        }

        
// Check if there is any xml from local copy
        
if (empty($xml)) {
            
// Doesn't exist yet or too old, get xml from AWS
            
$xml implode(" "file($url));
        }

        
// Parse xml into array
        
$data = &$this->parse($xml);

        // Destroy XML parser
        
$this->destruct();

        
// Get the product info
        
$data $data['ProductInfo'];

        
// Check for error message
        
if (!empty($data['ErrorMsg'])) {
            
// Get old cache copy, if any
            
if (file_exists ($cachefn)) { 
                
// Get xml from local cache
                
$xml implode(" "file($cachefn));
            } else {
                
// No cache, just return false and set error message
                
$this->error $data['ErrorMsg'];
                return 
false;
            }
        }

        
// Write local cache copy
        
$f fopen($cachefn"w");
        
fwrite($f$xml);
        
fclose($f);

        return 
$data;
    }

    function 
destruct(){ xml_parser_free(&$this->parser); }

    
function & parse(&$data){
        
$this->parser = &xml_parser_create();
        
xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);
        
xml_set_object(&$this->parser, &$this);
        
xml_set_element_handler(&$this->parser, 'open','close');
        
xml_set_character_data_handler(&$this->parser, 'data');

        
$this->document = array();
        
$this->stack    = array();
        
$this->parent   = &$this->document;
        
return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;
    
}
    function 
open(&$parser, $tag, $attributes){
        
$this->data ''#stores temporary cdata
        
$this->last_opened_tag $tag;
        if(
is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before
            
if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric
                #this is the third or later instance of $tag we've come across
                
$key count_numeric_items($this->parent[$tag]);
            }else{
                
#this is the second instance of $tag that we've seen. shift around
                
if(array_key_exists("$tag attr",$this->parent)){
                    
$arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);
                    
unset($this->parent["$tag attr"]);
                }else{
                    
$arr = array(&$this->parent[$tag]);
                
}
                
$this->parent[$tag] = &$arr;
                
$key 1;
            }
            
$this->parent = &$this->parent[$tag];
        
}else{
            
$key $tag;
        }

        
// If only URL attribute, add url to main array
        // Else, add attributes to seperate array
        
if (count($attributes) == AND !empty($attributes['url'])) {
            
$this->parent[$key]['url'] = $attributes['url'];
        } elseif (
$attributes) {
            
$this->parent["$key attr"] = $attributes;
        }


        
$this->parent       = &$this->parent[$key];
        
$this->stack[]      = &$this->parent;
    
}
    function 
data(&$parser, $data){
        
if($this->last_opened_tag != NULL#you don't need to store whitespace in between tags
            
$this->data .= $data;
    }
    function 
close(&$parser, $tag){
        
if($this->last_opened_tag == $tag){
            
$this->parent $this->data;
            
$this->last_opened_tag NULL;
        }
        
array_pop($this->stack);
        if(
$this->stack$this->parent = &$this->stack[count($this->stack)-1];
    
}
}

function 
count_numeric_items(&$array){
    
return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;
}

// Use this class like this:

// Include AWS Class
include ("aws.php")

// Create new instance of AWS class, inputing the developer token and associate id
$aws = &new AWS("[Dev Token Goes Here]", "aspit-20");

// Set cache directory
$aws->directory "/home/you/cache/";

// Get AWS data
// [associateid] and [devtoken] are automatically replaced by their values
$data $aws->go ("http://xml.amazon.com/onca/xml3?t=[associateid]&dev-t=[devtoken]&AsinSearch=0439139597&type=lite&f=xml");

// Do something with the data here
// ...
?>

Leave a Reply