<?php
// config.php loads the Amazon API key and other configuration details
// (you'll be asked for these when you clone this app)
require_once 'config/config.php';
// our Amazon API module
require_once 'XNC/Services/Amazon.php';
// introductory HTML welcome
require_once 'welcome.php';
// remove non-safe characters from the submitted query
// or use a default query if there isn't one
$query = $_GET['q'] ? xnhtmlentities($_GET['q']) : 'fish';
// print the form
?>
<form action="index.php" METHOD="GET">
<label for="q">Search term</label>
<input name="q" value="<?php echo $query ?>"/>
<input type="submit" value="Search Amazon Books"/>
</form>
<?php
// log into Amazon, using our config key
$amazon = new XNC_Services_Amazon(PrivateConfig::$amazonKey);
// execute a tag search
$response = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => $query, 'ResponseGroup' => 'Medium'));
// how'd we do?
echo "<h3>Showing {$response->totalResultsReturned}";
echo " of {$response->totalResultsAvailable} results.</h3>";
// finally, print the results in a table
?>
<table width="99%">
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Sales Rank</th>
</tr>
</thead>
<tbody>
<?php
// loop through all the objects returned by the query
foreach ($response->Result as $result)
{
// transform any non-safe characters in the book title
$safetitle = xnhtmlentities($result->Title);
// 'Author' could be single string or array
$author = is_array($result->Author)
? implode(', ', flatten($result->Author))
: $result->Author;
// print the table row with the object details
echo <<<_HTML_
<tr>
<td><a href="{$result->DetailPageURL}"><img
src="{$result->SmallImage->Url}"/></a></td>
<td><a href="{$result->DetailPageURL}">{$safetitle}</a></td>
<td>{$author}</td>
<td>{$result->SalesRank}</td>
</tr>
_HTML_;
}
// and we're done!
?>
</tbody>
</table>
<?php
// Amazon sends the book author data as nested elements which
// become nested arrays, which need to be flattened for display
function flatten($array)
{
$tmp = array();
foreach($array as $key => $value)
{
if(is_array($value))
$tmp = array_merge($tmp,flatten($value,$key));
else
$tmp[$key] = $value;
}
return $tmp;
}
?>