PEAR::Services_AmazonのSimilarityLookupで関連書籍を表示

PEAR::Services_AmazonのItemSearchでキーワード検索した書籍のASINを使用してSimilarityLookupを実行し、キーワード検索した書籍の関連書籍を表示させるプログラムを作成してみました。

 PHP 逆引きレシピ (PROGRAMMER’S RECiPE)
 鈴木 憲治 (著)
 翔泳社 より 2009-06-30 発売
 ロープライス ¥ 2,500 or 新品 ¥ 2,730
 
関連書籍 よくわかるPHPの教科書
ロープライス ¥ 3,333 or 新品 ¥ 2,604
関連書籍 PHPによるWebアプリケーションスーパーサンプル 第2版
ロープライス ¥ 2,900 or 新品 ¥ 3,990
関連書籍 パーフェクトPHP (PERFECT SERIES 3)
ロープライス ¥ 3,440 or 新品 ¥ 3,780
関連書籍 基礎からのMySQL [基礎からのシリーズ] (プログラマの種シリ…
ロープライス ¥ 2,700 or 新品 ¥ 3,129
関連書籍 Webサイト制作者のための PHP入門講座
ロープライス ¥ 2,734 or 新品 ¥ 3,129

上記が、実際に作成したプログラムの実行結果です。HTML表示部分は、WordPressの投稿ページ内で特殊タグ([exec]〜[/exec])に挟まれた部分のPHPコードをで実行出来る「WP exec PHP」プラグインを使用して、WordPressの投稿ページに表示を行っています。

末尾に実際のソースコードを添付いたしましたが、プログラムの概要としては以下のようなことを行いました。

  1. 「Services/Amazon.php」をインクルードファイルとして読み込む。
  2. 定数として、アクセスキー、シークレットアクセスキー、アソシエイトID、Amazon ECSのバージョン、タイトルの文字数などを定義しました。Amazon ECSのバージョンは、最新の「2011-08-02」を使用することにしました。
  3. 変数として、PEAR::Services_AmazonのItemSearchとSimilarityLookupで使用するキーワード、サーチインデックス、ソート順、IDタイプ、ページ制御を行う変数などを定義しました。
  4. 定数として定義したアクセスキーID、シークレットアクセスキー、アソシエイトIDを使用して、Services_Amazonの呼び出しを行いました。
  5. 変数として定義したオプション(サーチインデックス、キーワード、ソート順)でItemSearchのオプション設定を行った後、ItemSearchを実行し検索結果を配列に格納しました。
  6. 上記の検索結果を格納した配列から、For文のループで1件の検索結果を表示させました。
  7. 続いて、ItemSearchを実行して得られたASIN及び変数として定義したオプション(サーチインデックス、IDタイプ)でSimilarityLookupのオプション設定を行った後、SimilarityLookupを実行し検索結果を配列に格納しました。
  8. 上記の検索結果を格納した配列から、For文のループで製品表示数分の検索結果を表示させました。

以下に、実際のソースコードを添付いたします。

<?php
// インクルードファイル
require_once("Services/Amazon.php");
// 定数
define('ACCESSKEY_ID', 'xxxxxxxxxxxxxxxxxxxx');
define('SECRET_ACCESSKEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('ASSOCIATE_ID', 'xxxxxxxxxx-22');
define('ECS_VERSION','2011-08-02');
define('RESPONSE_GROUP','Small,Images,ItemAttributes,OfferSummary,');
define('TITLE_STR_MAX','60'); // タイトル文字数
// 変数
$keyword='PEAR PHP';
$search_index='Books';  // サーチインデックス
$id_type='ISBN';        // 'ASIN' 又は 'ISBN','EAN'
$sort= 'salesrank';
$show_num= '5';
$item_page= '1';
// Services_Amazonの呼び出し
$amazon = new Services_Amazon(ACCESSKEY_ID,SECRET_ACCESSKEY,ASSOCIATE_ID);
// ItemSearchのオプション設定
$amazon->setLocale('JP');
$options = array();
  $options['Keywords'] = $keyword;
  $options['Sort'] = $sort;
  $options['ResponseGroup'] = RESPONSE_GROUP;
  $options['ItemPage'] = $item_page;
// 検索結果を配列に格納
$result = $amazon->ItemSearch($search_index, $options);
// 検索結果の表示
echo '<table border="0" width="640" cellpadding="1" cellspacing="1">';
if (!PEAR::isError($result)) {
    for( $i = 0; $i < 1; $i++ ) {
        //データを変数に格納
        if(isset($result['Item'][$i]['DetailPageURL'])){ 
            $detail_page_url = $result['Item'][$i]['DetailPageURL'];
        }else{
            $detail_page_url = '';
        }
        if(isset($result['Item'][$i]['MediumImage']['URL'])){
            $medium_image = $result['Item'][$i]['MediumImage']['URL'];
        }else{
            $medium_image = '';
        }
        if(isset($result['Item'][$i]['MediumImage']['Width']['_content'])){
            $medium_image_width = $result['Item'][$i]['MediumImage']['Width']['_content'];
        }else{
            $medium_image_width = '130';
        }
        if(isset($result['Item'][$i]['ItemAttributes']['Title'])){
            $title = $result['Item'][$i]['ItemAttributes']['Title'];
        }else{
            $title = '無し';
        }
        if(isset($result['Item'][$i]['ItemAttributes']['Author'][0])){
            $author = $result['Item'][$i]['ItemAttributes']['Author'][0];
        }else{
            $author = '無し';
        }
        if(isset($result['Item'][$i]['ItemAttributes']['Publisher'])){
            $publisher = $result['Item'][$i]['ItemAttributes']['Publisher'];
        }else{
            $publisher = '';
        }
        if(isset($result['Item'][$i]['ItemAttributes']['PublicationDate'])){
            $publication_date = $result['Item'][$i]['ItemAttributes']['PublicationDate'];
        }else{
            $publication_date = '';
        }
        if(isset($result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'])){
            $list_price= $result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'];
        }
        if(isset($result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'])){
            $lowest_new_price= $result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'];
        }
        if(isset($result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'])){
            $lowest_used_price = $result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'];
        }
        if($list_price==0){
            $new_price=$lowest_new_price;
        }else{
            $new_price=$list_price;
        }
        //データを表示
        echo '<tr><td colspan="1" rowspan="5" width="'.$medium_image_width.'">';
        echo '<a href="'.$detail_page_url.'"><img src="'.$medium_image.'"/></a></td>';
        echo '<td colspan="2" rowspan="1"> <a href="'.$detail_page_url.'">'.$title.'</a></td></tr>';
        echo '<tr><td colspan="2" rowspan="1"> '.$author.' (著) </td></tr>';
        echo '<tr><td colspan="2" rowspan="1"> '.$publisher.' より  '.$publication_date.' 発売</td></tr>';
        echo '<tr><td colspan="2" rowspan="1"> <a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'</td></tr>';
        echo '<tr><td  colspan="2" rowspan="1">&nbsp;</td></tr>';
        //ASINを$id_codeにセット
        if(isset($result['Item'][$i]['ASIN'])){
            $id_code=$result['Item'][$i]['ASIN'];
        }
    }
}
// 関係書籍の表示
// SimilarityLookupのオプション設定
$amazon->setLocale('JP');
$options = array();
$options['ResponseGroup'] = RESPONSE_GROUP;
$options['SearchIndex'] = $search_index;
$options['IdType'] = $id_type;
//検索結果を配列に格納
$result = $amazon->SimilarityLookup($id_code, $options);
//検索結果の表示
if (!PEAR::isError($result)) {
  for( $i = 0; $i < $show_num; $i++ ) {
    //データを変数に格納
    if(isset($result['Item'][$i]['DetailPageURL'])){
        $detail_page_url = $result['Item'][$i]['DetailPageURL'];
    }else{
         $detail_page_url = '';
    }
    if(isset($result['Item'][$i]['SmallImage']['URL'])){
        $small_image = $result['Item'][$i]['SmallImage']['URL'];
    }else{
         $small_image = '-';
    }
    if(isset($result['Item'][$i]['SmallImage']['Width']['_content'])){
        $smallimage_width = $result['Item'][$i]['SmallImage']['Width']['_content'];
    }else{
         $smallimage_width = '75';
    }
    if(isset($result['Item'][$i]['ItemAttributes']['Title'])){
        $title = mb_strimwidth($result['Item'][$i]['ItemAttributes']['Title'], 0, TITLE_STR_MAX, "...");
    }else{
         $$title = '';
    }
    if(isset($result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'])){
        $list_price= $result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'];
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'])){
        $lowest_new_price= $result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'];
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'])){
        $lowest_used_price = $result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'];
    }
    if($list_price==0){
        $new_price=$lowest_new_price;
    }else{
        $new_price=$list_price;
    }
    //データを表示
    echo '<tr>';
    echo '<td rowspan="2" align="center">';
    echo '関連書籍';
    echo '</td>';
    echo '<td align="center" colspan="1" rowspan="2" width="'.$smallimage_width.'">';
    echo '<a href="'.$detail_page_url.'"><img src="'.$small_image.'"/></a>';
    echo '</td>';
    echo '<td style="font-size:x-small">';
    echo ' <a href="'.$detail_page_url.'">'.$title.'</a>';
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td style="font-size:x-small">';
    echo '<a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price;
    echo '</td>';
    echo '</tr>';
    }
}
echo '</table>';
?>

上記のプログラムは、Product Advertising APIを使用していますので、実際にプログラミングを実行するためには、【amazon アソシエイト】でユーザー登録を行って、AmazonのアソシエイトID、アクセスキーID、シークレットアクセスキーの入手が必要です。

AmazonのBrowseNodeを探索する

前の記事で紹介しました「PEAR::Services_AmazonのItemSearchでBrowseNodeを指定してランキング表示するプログラム」とその前の記事で紹介した「PEAR::Services_AmazonのBrowseNodeLookupでBrowseNode一覧を取得するプログラム」を合体して、AmazonのBrowseNodeを探索するプログラムを作成してみました。

[List]ボタンをクリックすると下層のBrowseNodeを探索し、[Item]ボタンをクリックすると該当するBrowseNodeで商品検索を行います。[List]ボタンをクリックして下層のBrowseNodeが無い場合も該当するBrowseNodeで商品検索を行います。



上記のプログラムは、Product Advertising APIを使用していますので、実際にプログラミングを実行するためには、【amazon アソシエイト】でユーザー登録を行って、AmazonのアソシエイトID、アクセスキーID、シークレットアクセスキーの入手が必要です。

PEAR::Services_AmazonのBrowseNodeLookupでBrowseNode一覧を取得

前の記事で紹介した「PEAR::Services_AmazonのItemSearchでBrowseNodeを指定してランキング表示」を行うためには、元になるBroeseNodeを知る必要が有ります。トップレベルのBrowseNodeは、「Product Advertising API開発者ガイド (API Version 2010-09-01)」に記載されている他、様々なものが存在するようです。

PEAR::Services_AmazonのBrowseNodeLookupでBrowseNodeを指定して検索すると、指定したBrowseNodeの下層にあるBrowseNode一覧を取得出来ますので、Product Advertising API開発者ガイド (API Version 2010-09-01)」に記載されているトップレベルBrowseNodeを起点として、その下層にあるBrowseNodeを検索するプログラムを作成してみました。プログラムの実行結果は、下記のようになります。

BrowseNode List


Apparel Root [ 361245011 ]-
2131417051メンズ
2131478051レディース
2131568051ボーイズ
2131590051ガールズ
345991011ベビー
2226725051スペシャリティアパレル
2247104051スポーツウェア

末尾に実際のソースコードを添付いたしましたが、プログラムの概要としては以下のようなことを行いました。

  1. 「Services/Amazon.php」をインクルードファイルとして読み込む。
  2. 定数として、アクセスキー、シークレットアクセスキー、アソシエイトID、Amazon ECSのバージョン他を定義しました。Amazon ECSのバージョンは、最新の「2011-08-02」を使用することにしました。
  3. 変数として、PEAR::Services_AmazonのBrowseNodeLookupで使用するブラウズノードの他、カテゴリー配列などを定義しました。
  4. フォーム送信されてくるリクエストの処理を行いました。
  5. 定数として定義したアクセスキーID、シークレットアクセスキー、アソシエイトIDを使用して、Services_Amazonの呼び出しを行いました。
  6. 変数として定義したブラウズノードを使用して、Services_AmazonのBrowseNodeLookupを実行し、検索結果を配列に格納しました。
  7. 上記で検索結果を格納した配列から、For文のループで製品表示数分の検索結果を表示させました。今回、「WP exec PHP」プラグインの使用を前提にしましたので、echo文を使用して、表示部分のHTMLのみを出力させました。

以下に、実際のソースコードを添付いたします。

<?php
// インクルードファイル
require_once('Services/Amazon.php');
// 定数
define('ACCESSKEY_ID', 'xxxxxxxxxxxxxxxxxxxx');
define('SECRET_ACCESSKEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('ASSOCIATE_ID', 'xxxxxxxxxx-22');
define('ECS_VERSION','2011-08-02');
define('RESPONSE_GROUP','Small');
define('SCRIPT_TITLE','BrowseNode List');
// 変数
$category_array=array(// カテゴリー配列
    array('index'=>'Apparel','name'=>'カテゴリーを選択してください','node'=>'361245011'),
    array('index'=>'Apparel','name'=>'服&ファッション小物','node'=>'361245011'),
    array('index'=>'Automotive','name'=>'カー&バイク用品','node'=>'2017305051'),
    array('index'=>'Baby','name'=>'ベビー&マタニティ ','node'=>'344919011'),
    array('index'=>'Beauty','name'=>'コスメ','node'=>'52391051'),
    array('index'=>'Books','name'=>'和書','node'=>'465610'),
    array('index'=>'Classical','name'=>'クラシック','node'=>'701040'),
    array('index'=>'DVD','name'=>'DVD','node'=>'562002'),
    array('index'=>'Electronics','name'=>'家電&カメラ','node'=>'3210991'),
    array('index'=>'ForeignBooks','name'=>'洋書','node'=>'52231011'),
    array('index'=>'Grocery','name'=>'食料品','node'=>'57240051'),
    array('index'=>'HealthPersonalCare','name'=>'ヘルス&ビューティー','node'=>'161669011'),
    array('index'=>'Jewelry','name'=>'ジュエリー','node'=>'85896051'),
    array('index'=>'Kitchen','name'=>'ホーム&キッチン','node'=>'3839151'),
    array('index'=>'Music','name'=>'音楽','node'=>'562032'),
    array('index'=>'Shoes','name'=>'シューズ&バッグ','node'=>'2016927051'),
    array('index'=>'Software','name'=>'PCソフト','node'=>'637630'),
    array('index'=>'SportingGoods','name'=>'スポーツ&アウトドア','node'=>'14315361'),
    array('index'=>'Toys','name'=>'おもちゃ','node'=>'13299551'),
    array('index'=>'VHS','name'=>'VHS','node'=>'561972'),
    array('index'=>'Video','name'=>'Video','node'=>'561972'),
    array('index'=>'VideoGames','name'=>'TVゲーム','node'=>'637872'),
    array('index'=>'Watches','name'=>'時計','node'=>'331952011'),
);
// カテゴリー配列初期値
$category_index='1'; // 配列のインデックス
$browse_node='361245011';// BrowseNodeId
$search_index='Apparel';// サーチインデックス
$name='';
// リクエストの処理
if(isset($_REQUEST['action'])){
    if($_REQUEST['action']=='カテゴリー変更'){
        if(isset($_REQUEST['category'])){
            $category_index=htmlspecialchars($_REQUEST['category']);
        }
        $browse_node=$category_array[$category_index]['node'];
        $search_index=$category_array[$category_index]['index'];
    }else if($_REQUEST['action']=='list'){
        if(isset($_REQUEST['category_index'])){
            $category_index=htmlspecialchars($_REQUEST['category_index']);
        }
        if(isset($_REQUEST['browse_node'])){
            $browse_node=htmlspecialchars($_REQUEST['browse_node']);
        }
        $search_index=$category_array[$category_index]['index'];
    }else{
        $category_index='1'; // 配列のインデックス
        $browse_node='361245011';// BrowseNodeId
        $search_index='Apparel';// サーチインデックス
    }
}
// Services_Amazonの呼び出し
$amazon = new Services_Amazon(ACCESSKEY_ID,SECRET_ACCESSKEY,ASSOCIATE_ID);
$amazon->setLocale('JP');
//検索結果を配列に格納
$result = $amazon->BrowseNodeLookup($browse_node);
// フォームの表示
echo '<h3>'.SCRIPT_TITLE.'</h3>';
echo '<form action="">';
echo '<select name="category">';
$i=0;
foreach ($category_array as $category) {
    if($i==$category_index){
        echo '<option value="'.$i.'"  selected>'.$category['name'];
    }else{
        echo '<option value="'.$i.'">'.$category['name'];
    }
    $i++;
}
echo '</select>';
echo '<input type="submit" name="action" value="カテゴリー変更">';
echo '</form>';
echo '<hr size="1" color="#cccccc" style="border-style:dashed">';
// 検索結果の表示
if (!PEAR::isError($result)) {
    if(isset($result['BrowseNode']['Children']['BrowseNode'])){
        $count_max=count($result['BrowseNode']['Children']['BrowseNode']);
        echo '<table border="1" width="640" cellpadding="0" cellspacing="0">';
        echo '<tbody>';
        echo '<tr style="background-color:#cccccc;">';
        echo '<th align="center">';
        echo $search_index;
        echo '</th>';
        echo '<th align="center"> Root [ ';
        echo $category_array[$category_index]['node'];
        echo ' ]</th>';
        echo '<th align="center">';
        if(isset($_REQUEST['action'])){
            echo '<form>';
            echo '<input type=button value=" 戻 る " onClick="self.history.back()" style="WIDTH: 80px; HEIGHT: 30px">';
            echo '</form>';
        }else{
            echo '-<br>';
        }
        echo '</th>';
        echo '</tr>';
        for( $i = 0; $i < $count_max; $i++ ) {
            //データを変数に格納
            $browse_node_id=$result['BrowseNode']['Children']['BrowseNode'][$i]['BrowseNodeId'];
            $name=$result['BrowseNode']['Children']['BrowseNode'][$i]['Name'];
            //データを表示
            echo '<tr>';
            echo '<td width="200" align="center">'.$browse_node_id.'</td>';
            echo '<td width="300">'.$name.'</td>';
            echo '<td align="center">';
            echo '<form action="">';
            echo '<input type="hidden" name="action" value="list">';
            echo '<input type="hidden" name="browse_node" value="'.$browse_node_id.'">';
            echo '<input type="hidden" name="category_index" value="'.$category_index.'">';
            echo '<input type="hidden" name="name" value="'.$name.'">';
            echo '<input type="submit" value="下層へ" style="WIDTH: 80px; HEIGHT: 30px">';
            echo '</form>';
            echo '</td>';
            echo '<tr>';
        }
        echo '</tbody>';
        echo '</table>';
    }else{
        echo '<table border="1" width="640" cellpadding="0" cellspacing="0">';
        echo '<tbody>';
        echo '<tr>';
        echo '<th align="center">';
        echo $search_index;
        echo '</th>';
        echo '<th align="center"> Root [ ';
        echo $category_array[$category_index]['node'];
        echo ' ]</th>';
        echo '<th align="center">';
        echo '<form>';
        echo '<input type=button value=" 戻 る " onClick="self.history.back()" style="WIDTH: 80px; HEIGHT: 30px">';
        echo '</form>';
        echo '</th>';
        echo '</tr>';
        echo '<tr>';
        echo '<td width="200" align="center">'.$browse_node.'</td>';
        echo '<td width="300">'.$_REQUEST['name'].'</td>';
        echo '<td align="center">---';
        echo '</td>';
        echo '</tr>';
        echo '<tr><td colspan="3">下層にノードがありませんでした。</td></tr>';
        echo '</tbody>';
        echo '</table>';
    }
}
?>

上記プログラムで検索して判明した「フルハイビジョン液晶テレビ」のBroeseNode「615940011」を使用して、前の記事で作成したプログラムで「フルハイビジョン液晶テレビ」のランキングを表示すると、以下のようになります。

【 フルハイビジョン液晶テレビ 】ベスト 5
 TOSHIBA 3D対応LED REGZA 32V型 地上・BS・110度CSデジタルフ…
【 東芝 】新品価格:¥ 53,994/中古価格:(無し)
 TOSHIBA REGZA 40V型地上・BS・110度CSデジタルフルハイビジ…
【 東芝 】新品価格:¥ 44,191/中古価格:(無し)
 Panasonic VIERA 37V型 地上・BS・110度CSデジタルハイビジョ…
【 パナソニック 】新品価格:¥ 40,120/中古価格:(無し)
 TOSHIBA REGZA 37V型 地上・BS・110度CSデジタルフルハイビジ…
【 東芝 】新品価格:¥ 69,000/中古価格:(無し)
 SONY 3D対応地上・BS・110度CSデジタルハイビジョン液晶テレ…
【 ソニー 】新品価格:¥ 66,800/中古価格:(無し)

上記のプログラムは、Product Advertising APIを使用していますので、実際にプログラミングを実行するためには、【amazon アソシエイト】でユーザー登録を行って、AmazonのアソシエイトID、アクセスキーID、シークレットアクセスキーの入手が必要です。

PEAR::Services_AmazonのItemSearchでBrowseNodeを指定してランキング表示

PEAR::Services_Amazon のItemSearchでBrowseNodeを指定して検索すると、そのBrowseNodeの商品情報が得られます。Sort順に’salesrank’を指定して検索すれば、そのBrowseNodeのセールスランキングが表示出来ます。

今回、PEAR::Services_AmazonのItemSearchと「WP exec PHP」プラグインを連携させて、WordPressの投稿ページに特定BrowseNodeのセールスランキングを表示させるプログラムを作成してみました。サーチインデクスに’Electronics’、BrowseNodeに「デジタル一眼レフ/エントリー」の’387465011′を指定した実行結果は、下記のようになります。

【 デジタル一眼レフ/エントリー 】ベスト 5
 Canon デジタル一眼レフカメラ EOS Kiss X5 ダブルズームキッ…
【 キヤノン 】新品価格:¥ 63,000/中古価格:¥ 65,000
 Canon デジタル一眼レフカメラ EOS Kiss X4 ダブルズームキッ…
【 キヤノン 】新品価格:¥ 53,124/中古価格:¥ 52,000
 Canon デジタル一眼レフカメラ EOS 60D ダブルズームキット E…
【 キヤノン 】新品価格:¥ 84,987/中古価格:(無し)
 Nikon デジタル一眼カメラ Nikon 1 (ニコンワン) J1 (ジェイ…
【 ニコン 】新品価格:¥ 35,980/中古価格:¥ 33,800
 OLYMPUS マイクロ一眼 PEN E-PL2 レンズキット ゴールド E-PL…
【 オリンパス 】新品価格:¥ 32,800/中古価格:(無し)

末尾に実際のソースコードを添付いたしましたが、プログラムの概要としては以下のようなことを行いました。

  1. 「Services/Amazon.php」をインクルードファイルとして読み込む。
  2. 定数として、アクセスキー、シークレットアクセスキー、アソシエイトID、Amazon ECSのバージョン他を定義しました。Amazon ECSのバージョンは、最新の「2011-08-02」を使用することにしました。
  3. 変数として、PEAR::Services_AmazonのItemSearchで使用するサーチインデックス、オプション(ブラウズノード、ソート順)及び製品表示数を制御する変数などを定義しました。
  4. 定数として定義したアクセスキーID、シークレットアクセスキー、アソシエイトIDを使用して、Services_Amazonの呼び出しを行いました。
  5. 変数として定義したサーチインデックス、オプション(ブラウズノード、ソート順)を使用して、Services_AmazonのItemSearch検索結果を配列に格納しました。
  6. 上記で検索結果を格納した配列から、For文のループで製品表示数文の検索結果を表示させました。今回、「WP exec PHP」プラグインの使用を前提にしましたので、echo文を使用して、表示部分のHTMLを出力させました。

以下に、実際のソースコードを添付いたします。

<?php
//  インクルードファイル
require_once('Services/Amazon.php');
// 定数
define('ACCESSKEY_ID', 'xxxxxxxxxxxxxxxxxxxx');
define('SECRET_ACCESSKEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('ASSOCIATE_ID', 'xxxxxxxxxx-22');
define('ECS_VERSION','2011-08-02');
define('RESPONSE_GROUP','Small,Images,ItemAttributes,OfferSummary,');
define('TITLE_STR_MAX','60'); // タイトル文字数
// 変数
$browse_node_name= 'デジタル一眼レフ/エントリー';
$search_index= 'Electronics';
$browse_node= '387465011';
$sort= 'salesrank';
$item_page= '1';
$show_num= '5'; // 最小1〜最大10
// Services_Amazonの呼び出し
$amazon = new Services_Amazon(ACCESSKEY_ID,SECRET_ACCESSKEY,ASSOCIATE_ID);
$amazon->setLocale('JP');
$options = array();
    $options = array();
    $options['BrowseNode'] = $browse_node;
    $options['Sort'] = $sort;
    $options['ResponseGroup'] = RESPONSE_GROUP;
    $options['ItemPage'] = $item_page;
//検索結果を配列に格納
$result = $amazon->ItemSearch($search_index,$options);
//検索結果の表示
if (!PEAR::isError($result)) {
  echo '<div style="border: 1px solid gray; background-color:#cccccc;">';
  echo '【 '.$browse_node_name.' 】'.'ベスト '.$show_num;
  echo '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
  echo '<tbody style="border: 1px solid gray; background-color:#ffffff;font-size: x-small;">';
  if($show_num<0){ $show_num=1; }
  if($show_num>=10){ $show_num=10; }
  for( $i = 0; $i < $show_num; $i++ ) {
    //データを変数に格納
    $detail_page_url = $result['Item'][$i]['DetailPageURL'];
    $title = mb_strimwidth($result['Item'][$i]['ItemAttributes']['Title'], 0, TITLE_STR_MAX, "...");
    $publisher = $result['Item'][$i]['ItemAttributes']['Publisher'];
    if(isset($result['Item'][$i]['SmallImage']['URL'])){
        $small_image = $result['Item'][$i]['SmallImage']['URL'];
        $width = $result['Item'][$i]['SmallImage']['Width']['_content'];
        $height = '75';
    }else{
        $small_image = '0';
        $width = '75';
        $height = '75';
    }
    // 価格
    if(isset($result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'])){
        $list_price= $result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'];
    }else{
        $list_price=0;
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'])){
        $lowest_new_price= $result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'];
    }else{
        $lowest_new_price= '(無し)';
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'])){
        $lowest_used_price = $result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'];
    }else{
        $lowest_used_price= '(無し)';
    }
    if($list_price==0){
        $new_price=$lowest_new_price;
    }else{
        $new_price=$list_price;
    }
    //データを表示
    if($i%2){
        echo '<tr style="background-color:#fafafa;">';
    }else{
        echo '<tr style="background-color:#ffffff;">';
    }
    if($small_image=='0'){
        echo '<td colspan="1" rowspan="2" width="'.$width.'" height="'.$height.'"> </td>';
    }else{
        echo '<td colspan="1" rowspan="2" width="'.$width.'" height="'.$height.'">';
        echo '<a href="'.$detail_page_url.'"><img src="'.$small_image.'"/></a></td>';
    }
    echo '<td> <a href="'.$detail_page_url.'">'.$title.'</a></td></tr>';
    if($i%2){
        echo '<tr style="background-color:#fafafa;">';
    }else{
        echo '<tr style="background-color:#ffffff;">';
    }
    echo '<td>【 '.$publisher.' 】新品価格:'.$new_price.'/中古価格:'.$lowest_used_price.'</td></tr>';
  }
  echo '</tbody>';
  echo '</table>';
  echo '</div>';
}
?>

上記のプログラムは、Product Advertising APIを使用していますので、実際にプログラミングを実行するためには、【amazon アソシエイト】でユーザー登録を行って、AmazonのアソシエイトID、アクセスキーID、シークレットアクセスキーの入手が必要です。

PEAR::Services_AmazonのItemSearchと「WP exec PHP」プラグインの連携

PEAR::Services_AmazonのItemSearchと「WP exec PHP」プラグインを連携させて、WordPressの投稿ページにAmazonでキーワード検索した商品を表示させるプログラムを作成してみました。

 采配
 【落合博満】
 ダイヤモンド社 より 2011-11-17 発売
 ロープライス ¥ 980 or 新品 ¥ 1,575
 

 スティーブ・ジョブズ I
 【ウォルター・アイザックソン】
 講談社 より 2011-10-25 発売
 ロープライス ¥ 1,130 or 新品 ¥ 1,995
 

上記が、実際に作成したプログラムの実行結果です。WordPressの投稿ページ内で特殊タグ([exec]〜[/exec])に挟まれた部分のPHPコードをで実行出来る「WP exec PHP」プラグインを使用して表示させています。

末尾に実際のソースコードを添付いたしましたが、プログラムの概要としては以下のようなことを行いました。

  1. 「Services/Amazon.php」をインクルードファイルとして読み込む。
  2. 定数として、アクセスキー、シークレットアクセスキー、アソシエイトID、Amazon ECSのバージョンを定義しました。Amazon ECSのバージョンは、最新の「2011-08-02」を使用することにしました。
  3. 変数として、PEAR::Services_AmazonのItemSearchで使用するサーチインデックス、オプションと製品表示数を制御する変数を定義しました。
  4. 定数として定義したアクセスキーID、シークレットアクセスキー、アソシエイトIDを使用して、Services_Amazonの呼び出しを行いました。
  5. 変数として定義したサーチインデックス、オプションを使用して、Services_AmazonのItemSearch検索結果を配列に格納しました。
  6. 上記で検索結果を格納した配列から、For文のループで製品表示数分の検索結果を表示させました。今回、「WP exec PHP」プラグインの使用を前提にしましたので、echo文を使用して、表示部分のHTMLを出力させました。

以下に、実際のソースコードを添付いたします。

<?php
//  インクルードファイル
require_once('Services/Amazon.php');
// 定数
define('ACCESSKEY_ID', 'xxxxxxxxxxxxxxxxxxxx');
define('SECRET_ACCESSKEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('ASSOCIATE_ID', 'xxxxxxxxxx-22');
define('ECS_VERSION','2011-08-02');
define('RESPONSE_GROUP','Small,Images,ItemAttributes,OfferSummary,');
// 変数
$search_index = 'Books';
$keyword='スティーブ・ジョブズ';
$sort = 'salesrank';
$item_page='1';
$show_num='2';
// Services_Amazonの呼び出し
$amazon = new Services_Amazon(ACCESSKEY_ID,SECRET_ACCESSKEY,ASSOCIATE_ID);
$amazon->setLocale('JP');
$options = array();
  $options['Keywords'] = $keyword;
  $options['Sort'] = $sort;
  $options['ResponseGroup'] = RESPONSE_GROUP;
  $options['ItemPage'] = $item_page;
//検索結果を配列に格納
$result = $amazon->ItemSearch($search_index, $options);
//検索結果の表示
if (!PEAR::isError($result)) {
  for( $i = 0; $i < $show_num; $i++ ) {
    //データを変数に格納
    $detail_page_url = $result['Item'][$i]['DetailPageURL'];
    $medium_image = $result['Item'][$i]['MediumImage']['URL'];
    $medium_image_width = $result['Item'][$i]['MediumImage']['Width']['_content'];
    $title = $result['Item'][$i]['ItemAttributes']['Title'];
    $author = $result['Item'][$i]['ItemAttributes']['Author'][0];
    $publisher = $result['Item'][$i]['ItemAttributes']['Publisher'];
    $publication_date = $result['Item'][$i]['ItemAttributes']['PublicationDate'];
    if(isset($result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'])){
        $list_price= $result['Item'][$i]['ItemAttributes']['ListPrice']['FormattedPrice'];
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'])){
        $lowest_new_price= $result['Item'][$i]['OfferSummary']['LowestNewPrice']['FormattedPrice'];
    }
    if(isset($result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'])){
        $lowest_used_price = $result['Item'][$i]['OfferSummary']['LowestUsedPrice']['FormattedPrice'];
    }
    if($list_price==0){
        $new_price=$lowest_new_price;
    }else{
        $new_price=$list_price;
    }

    //データを表示
    echo '<div style="border: 1px solid gray;">';
    echo '<table border="0" width="100%" cellpadding="2" cellspacing="2">';
    echo '<tbody>';
    echo '<tr><td colspan="1" rowspan="5" width="'.$medium_image_width.'">';
    echo '<a href="'.$detail_page_url.'"><img src="'.$medium_image.'"/></a></td>';
    echo '<td> <a href="'.$detail_page_url.'">'.$title.'</a></td></tr>';
    echo '<tr><td> 【'.$author.'】</td></tr>';
    echo '<tr><td> '.$publisher.' より  '.$publication_date.' 発売</td></tr>';
    echo '<tr><td> <a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'</td></tr>';
    echo '<tr><td >&nbsp;</td></tr>';
    echo '</tbody>';
    echo '</table>';
    echo '</div>';
    echo '<br />';
    }
}

上記のプログラムは、Product Advertising APIを使用していますので、実際にプログラミングを実行するためには、【amazon アソシエイト】でユーザー登録を行って、AmazonのアソシエイトID、アクセスキーID、シークレットアクセスキーの入手が必要です。