PA API Browsenode browser

Jump to: navigation, search

This is the code for a PHP page that allows you to traverse the browsenode tree of Amazon's Product Advertising API. I save it as "bnBrowse.php" on a testing domain on my home computer. The script must have access to paapi.php. You may also be interested in PA API Query Tester.

<?php  
ini_set('display_errors','Off');
//ini_set('display_errors','On');
error_reporting(E_ALL ^ E_NOTICE);
 
require_once('paapi.php');
 
$body = <<<bodtxt
<html xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Copyright (c) Kenneth Lucius.
*
* This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
*
*    http://creativecommons.org/licenses/by-nc-sa/3.0/
*
-->
    <title>BrowseNode Info</title>
 
    <style type="text/css">
        #xmltext p {
            padding:0;
            margin:0;
        }
        #xmltext p.item {
            background-color:#def;
        }
        #xmltext p.error {
            background-color:#fdd;
        }
 
        span.xtag { 
            color: #66a;
        }
        span.xclose { 
            color: #aaa;
        }
        ul.linklist, ul.linklist li {
            display: inline;
            list-style: none ;
            padding: 0 0.2em;
            margin: 0;
        }
    h1 {
        font-size:1.5em;
        border-bottom: solid gray 1px;
    }
    td, th {
        vertical-align:top;
        padding:0.5em 0.3em;
    }
    th {
        text-align:right
    }
    ul, li {
        padding-top: 0px;
        margin: 0px;
    } 
    </style>
</head>
<body>
<p>Also: <a href="./index.php">PA API: Define Query</a></p>
bodtxt;
 
$body .= '<h3>Locale: '.paapi::$amz_locale. '<br/> Others:' . paapi::get_locale_list('./bnBrowse.php') . '</h3>';
 
/* if no node specified in the URL, 
   display top-level nodes */
 
if(! $_GET['bn']) { 
    $body .= '<h1>'.$amz_locale.' Top Nodes</h1>';
    show_waiting( 'Retrieving '.count(paapi::$top_browse_nodes).' Top Nodes from Amazon API...');
    $lookedup = lookup_browsenode_batch(paapi::$top_browse_nodes);
    $sort = array();
    foreach(paapi::$top_browse_nodes as $t => $n) {
        if($lookedup[$n]) {
            $node = process_bn_xml($lookedup[$n]);
            if($node['ancestors'] && count($node['ancestors'])>0) { /* use only the top ancestor */
                $n = reset($node['ancestors']);
                $i = key($node['ancestors']);
                if(!  $n) {
                    print_r($lookedup[$n]);die();
                }
            }
            else {
                $n = $node['title'];
                $i = $node['id'];
            }
            $sort[$n.$i] = '<li>'.alink($i, $n).'</li>';
            //$body .= '<li>'.alink($i, $n).'</li>';
        }
        else { //bn not found
            $sort[$t.$n] = "<li>$t [$n] </li>";
            //$body .= "<li>$t [$n] </li>";
        }
 
    }
    ksort($sort);
    $body .= '<ul>' . implode("\n", $sort) . '</ul>';
}
 
/* else if a node WAS specified in the URL
   query it, process the XML, and display HTML */
 
else {
    if(! $_GET['xml']) {
        show_waiting( 'Querying Amazon API...');
        $xml = lookup_browsenode($_GET['bn']);
    }
    else {
        $xml = lookup_browsenode($_GET['bn'],true);
        paapi::dump_xml($xml);
        exit();
    }
    $node = process_bn_xml($xml->BrowseNodes->BrowseNode);
    if(! $node) {
        $msg = (string)$xml->BrowseNodes->Request->Errors->Error->Message;
        if($msg) $msg = "API error: $msg";
        $node = array('id'=>$_GET['bn'], 'title'=>'not found', 'msg'=>$msg);
    }
    $body .=  node_html($node);
}
 
 
/* a function to BrowseNodeLookup on the Amazon API */
 
function lookup_browsenode($bn=0, $raw=false) {
    $q = array( 'Operation'=>'BrowseNodeLookup', 
                'BrowseNodeId'=>$bn, 
                'ResponseGroup'=>'BrowseNodeInfo');
    $xml = paapi::get_xml_obj($q, $raw); 
    return $xml;
}
 
/* a function to BrowseNodeLookup many browsenodes 
   in batches of 10 */
 
function lookup_browsenode_batch($bnarr) {
    if(! is_array($bnarr) ) return false;
    $chunk = array_chunk($bnarr, 10);
    $ret = array();
    //temporarily floor it for the batch
    $th = paapi::$throttle;
    paapi::$throttle = 0.7; //setting it a bit tight for this burst of queries
    foreach($chunk as $bns) {
        $q = array( 'Operation'     =>'BrowseNodeLookup', 
                    'ResponseGroup' =>'BrowseNodeInfo',
                    'BrowseNodeId'  => implode(',',$bns) );
        $xml = paapi::get_xml_obj($q);
        foreach($xml->BrowseNodes->BrowseNode as $bnxml) {
            $ret[(string)$bnxml->BrowseNodeId] = $bnxml;
        }
    }
    paapi::$throttle = $th;
    return $ret;
}
 
/* accept an array containing node info and 
   return formatted HTML for display */
 
function node_html($node) {
    global $amz_locale;
    $str = '<h1>'.$amz_locale.' node '.$node['id'].': '.$node['title'].'</h1>';
    if($node['msg']) 
        $str .= '<p>' .$node['msg']. '</p>';
    if(count($node)<3)
        return $str;
 
    $str .= '<table class="bninfo">';
    $str .= '<tr><th>BrowseNodeId:</th><td>'.$node['id'].'</td></tr>'
            . '<tr><th>Name:</th><td>'      .$node['title'].'</td></tr>';
 
    $str .= '<tr><th>IsCategoryRoot:</th><td>';
    if(isset($node['IsRoot']))
        $str .= ($node['IsRoot']?'Yes':'No');
    $str .= '</td></tr>';
 
    $str .= '<tr><th>Ancestors:</th><td>' .alink(0, 'Root');
    $indent .= '<br /> &nbsp; ';
    if($node['ancestors']) {
        foreach($node['ancestors'] as $id=>$n) {
            $str .= $indent . alink($id,$n) ;
            $indent .= '&nbsp; ';
        }
 
    }
    $str .= $indent . alink($node['id'], $node['title']).'</td></tr>';
 
    $str .= '<tr><th>Children:</th><td>';
    if($node['children']) {
        $str .= '<ul>';
        foreach($node['children'] as $id=>$n) {
            $str .= '<li>'.alink($id, $n).'</li>';
        }
        $str .= '</ul>';
    }
    else {
        $str .= 'No Children'.'</td></tr>';
    }
    $str .= '</td></tr>';
    $str .= '</table>';
    return $str;
}
 
/* convenience function for displaying a browsenode linked to
   its display URL unless the its the one already being displayed */
 
function alink($id, $name) {
    global $amz_locale;
    if($_GET['bn'] == $id) {
        return '<b>'.$name.' <small>['.$id.']</small></b>';
    }
    return '<a href="bnBrowse.php?loc='.$amz_locale.'&bn='.$id.'">'.$name.' <small>['.$id.']</small></a>';
}
 
 
/* accept a SimpleXML object, pick out the relevant info
   cast as strings, return an array */
 
function process_bn_xml($xml) {
    if(! $xml->Name) {
        return false;
    }
    $xml = $xml;
 
    $node['id'] = (string)$xml->BrowseNodeId;
    $node['title'] = (string)$xml->Name;
    $node['IsRoot'] = (BOOL)$xml->IsCategoryRoot;
 
    if($xml->Children->BrowseNode) foreach($xml->Children->BrowseNode as $n) {
        $node['children'][ (string)$n->BrowseNodeId ] = (string)$n->Name;
    }
    if($xml->Ancestors->BrowseNode){
        $a = $xml;
        while($a = $a->Ancestors->BrowseNode){
            $node['ancestors'][ (string)$a->BrowseNodeId ] = (string)$a->Name;
        }
        $node['ancestors'] = array_reverse($node['ancestors'], true);
    }
    return $node;
}
 
/* print a "waiting" message to browser which is hidden when script exits */
 
function show_waiting($msg) {
    global $body;
    print( $body . '<span class="waiting">'.$msg.'</span>');
    $body = '';
    flush();
}
 
/* display the HTML page */
print($body);
?>
<style type="text/css">.waiting{visibility:hidden;}</style>
</body><html>
 
Personal tools