Oh!Happy.JP

さくらのVPS1GでWordPressブログはじめました

PEAR::Services_Amazonで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


Electronics Root [ 3210991 ] -
16462091 カメラ
3477381 テレビ・レコーダー
16462081 オーディオ
3371411 ポータブルオーディオ
124048011 家電
3371421 アクセサリ・サプライ
128187011 携帯電話
2111178051 カーナビ・カーAV
387483011 無線・トランシーバー
2313209051 商品延長保証

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

  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='8'; // 配列のインデックス
$browse_node='3210991';// BrowseNodeId
$search_index='Electronics';// サーチインデックス
$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


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

Amazon.Oh!Happy.JPでは、『PEAR(PHPで利用する事ができるライブラリ)のServices_Amazonというライブラリを使用して作成した「Amazon アソシエイト Web サービス(Product Advertising API)のサンプルプログラム(Sample)」を簡単な解説記事(Article)とソースコード(Code)とともに紹介しています。』ので、ご興味のある方はご覧ください。

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

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


 『PHP 逆引きレシピ (PROGRAMMER’S RECiPE)
 【鈴木 憲治】
 翔泳社 より 2009-06-30 発売
 ☆ ロープライス ¥ 2,270 or 新品 ¥ 2,730
 『よくわかるPHPの教科書
 ☆ ロープライス ¥ 2,100 or 新品 ¥ 2,604
 『PHPによるWebアプリケーションスーパーサンプル 第2版
 ☆ ロープライス ¥ 1,999 or 新品 ¥ 3,990
 『パーフェクトPHP (PERFECT SERIES 3)
 ☆ ロープライス ¥ 3,439 or 新品 ¥ 3,780
 『いきなりはじめるPHP~ワクワク・ドキドキの入門教室~
 ☆ ロープライス ¥ 3,319 or 新品 ¥ 1,890
 『基礎からのMySQL [基礎からのシリーズ] (プログラマの種シリーズ)
 ☆ ロープライス ¥ 2,500 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文のループで製品表示数分の検索結果を表示させました。今回、「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'); // タイトル文字数
// 変数
$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);
$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 < 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'];
        }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;
        }
        //データを表示
        echo '<dl style="font-size:x-small; width:640;">';
        echo '<dt style="float:left; width:'.$medium_image_width.';">';
            echo '<a href="'.$detail_page_url.'"><img src="'.$medium_image.'"/></a>';
        echo '</dt>';
        echo '<dd style="margin-left:0; padding-left:'.$medium_image_width.';">';
            echo '&nbsp;『<a href="'.$detail_page_url.' ">'.$title.'</a>』<br>';
            echo '&nbsp;【'.$author.'】<br>';
            echo '&nbsp;'.$publisher.' より  '.$publication_date.' 発売<br>';
            echo '&nbsp;☆&nbsp;<a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'<br>';
        echo '</dd>';
        echo '</dl>';
        echo '<div style="clear: both"></div>';

        //ASINを$id_codeにセット
        if(isset($result['Item'][$i]['ASIN'])){
            $id_code=$result['Item'][$i]['ASIN'];
        }
    }
}
// 関係書籍の表示
// Services_Amazonの呼び出し
//$amazon = new Services_Amazon(ACCESSKEY_ID,SECRET_ACCESSKEY,ASSOCIATE_ID);
$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 '<dl style="font-size:x-small; width:640;">';
        echo '<dt style="float:left; width:'.$smallimage_width.';">';
            echo '<a href="'.$detail_page_url.'"><img src="'.$small_image.'"/></a>';
        echo '</dt>';
        echo '<dd style="margin-left:0; padding-left:'.$smallimage_width.';">';
            echo '&nbsp;『<a href="'.$detail_page_url.' ">'.$title.'</a>』<br>';
            echo '&nbsp;☆&nbsp;<a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'<br>';
        echo '</dd>';
    echo '</dl>';
    echo '<div style="clear: both"></div>';
    }
}
?>

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

Amazon.Oh!Happy.JPでは、『PEAR(PHPで利用する事ができるライブラリ)のServices_Amazonというライブラリを使用して作成した「Amazon アソシエイト Web サービス(Product Advertising API)のサンプルプログラム(Sample)」を簡単な解説記事(Article)とソースコード(Code)とともに紹介しています。』ので、ご興味のある方はご覧ください。

PEAR::Services_AmazonのItemSearchででランキング表示

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

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


【 デジタル一眼レフ/エントリー 】ベスト 5


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

  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','100'); // タイトル文字数
// 変数
$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)) {
  if($show_num<0){ $show_num=1; }
  if($show_num>=10){ $show_num=10; }
  echo '<h3>【 '.$browse_node_name.' 】'.'ベスト '.$show_num.'</h3>';
  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'];
    $medium_image = $result['Item'][$i]['MediumImage']['URL'];
    $medium_image_width = $result['Item'][$i]['MediumImage']['Width']['_content'];
    $medium_image_height = $result['Item'][$i]['MediumImage']['Height']['_content'];
    // 価格
    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;
    }
    //データを表示
    echo '<div style="clear:both; font-size:x-small; width:640;">';
    echo '<dl>';
        echo '<dt style="float:left; width:'.$medium_image_width.'; height:'.$medium_image_height.';">';
            echo '<a href="'.$detail_page_url.'"><img src="'.$medium_image.'"/></a>';
        echo '</dt>';
        echo '<dd style="margin-left:0; padding-left:'.$medium_image_width.'; height:'.$medium_image_height.';">';
            echo '&nbsp;【'.$publisher.'】<br>';
            echo '&nbsp;『<a href="'.$detail_page_url.' ">'.$title.'</a>』<br>';
            echo '&nbsp;☆&nbsp;<a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'<br>';
        echo '</dd>';
    echo '</dl>';
    echo '</div>';
    }
}
?>

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

Amazon.Oh!Happy.JPでは、『PEAR(PHPで利用する事ができるライブラリ)のServices_Amazonというライブラリを使用して作成した「Amazon アソシエイト Web サービス(Product Advertising API)のサンプルプログラム(Sample)」を簡単な解説記事(Article)とソースコード(Code)とともに紹介しています。』ので、ご興味のある方はご覧ください。

PEAR::Services_AmazonのItemSearch

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


 『体系的に学ぶ 安全なWebアプリケーションの作り方 脆弱性が生まれる原理と対策の実践
 【徳丸 浩】
 ソフトバンククリエイティブ より 2011-03-03 発売
 ☆ ロープライス ¥ 3,989 or 新品 ¥ 3,360
 『よくわかるPHPの教科書
 【たにぐち まこと】
 毎日コミュニケーションズ より 2010-09-14 発売
 ☆ ロープライス ¥ 2,100 or 新品 ¥ 2,604
 『いきなりはじめるPHP~ワクワク・ドキドキの入門教室~
 【谷藤賢一】
 リックテレコム より 2011-12-09 発売
 ☆ ロープライス ¥ 3,319 or 新品 ¥ 1,890
 『プロになるための PHPプログラミング入門
 【星野 香保子】
 技術評論社 より 2012-01-13 発売
 ☆ ロープライス ¥ 2,499 or 新品 ¥ 2,814
 『パーフェクトPHP (PERFECT SERIES 3)
 【小川 雄大】
 技術評論社 より 2010-11-12 発売
 ☆ ロープライス ¥ 3,439 or 新品 ¥ 3,780

上記が、実際に作成したプログラムの実行結果です。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='PHPプログラミング';
$sort = 'salesrank';
$item_page='1';
$show_num='5';
// 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 '<dl style="font-size:x-small; width:640;">';
        echo '<dt style="float:left; width:'.$medium_image_width.';">';
            echo '<a href="'.$detail_page_url.'"><img src="'.$medium_image.'"/></a>';
        echo '</dt>';
        echo '<dd style="margin-left:0; padding-left:'.$medium_image_width.';">';
            echo '&nbsp;『<a href="'.$detail_page_url.' ">'.$title.'</a>』<br>';
            echo '&nbsp;【'.$author.'】<br>';
            echo '&nbsp;'.$publisher.' より  '.$publication_date.' 発売<br>';
            echo '&nbsp;☆&nbsp;<a href="'.$detail_page_url.'">ロープライス '.$lowest_used_price.'</a> or 新品 '.$new_price.'<br>';
        echo '</dd>';
    echo '</dl>';
    echo '<div style="clear: both"></div>';
    }
}
?>

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

Amazon.Oh!Happy.JPでは、『PEAR(PHPで利用する事ができるライブラリ)のServices_Amazonというライブラリを使用して作成した「Amazon アソシエイト Web サービス(Product Advertising API)のサンプルプログラム(Sample)」を簡単な解説記事(Article)とソースコード(Code)とともに紹介しています。』ので、ご興味のある方はご覧ください。