書籍”公開API活用ガイド”の第5章:アフィリエイト・リンクを読んで実践。
まずは、RWSのデベロッパーIDとアフィリエイトIDを取得した。
書籍では、”楽天商品検索API”を利用し、人気スイーツを表示するPHPプログラムを解説していた。
メモ
- リクエストURLの形式:http://api.rakuten.co.jp/rws/[version]/[schema]?[parameter]=[value]…
- versionとschemaが必須
- schemaは、REST、JSON、JSONP形式のどれか。REST形式は前回やった。今回もREST形式。
- PHPのfile_get_contents関数でリクエストURLからXMLファイルを取得
- simplexml_load_string関数でXMLファイルをパース
- パースして取得したオブジェクトのxpathメソッド?でItem要素だけを抽出
- クレジット表示解説ページ:http://webservice.rakuten.co.jp/credit/
フォームに入力した検索ワードを一覧表示するページ
確認:rakuten.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>楽天ウェブサービス(RWS) API practice</title>
</head>
<body>
<h1>楽天ウェブサービス(RWS) API sample</h1>
<form action="" method="get">
<input type="text" name="keyword" size="35" maxlength="255" value="" />
<input type="submit" value="search" />
</form>
<?php
function search_rakuten($keyword, $limit) {
$developerId = 'RWS developerID';
$affiliateId = 'RWS affiliateID';
$operation = 'ItemSearch';
$version = '2010-09-15';
$text = urlencode($keyword);
$hits = $limit;
$sort = urlencode("+itemPrice");
$url = 'http://api.rakuten.co.jp/rws/3.0/rest?'.
'developerId='.$developerId.
'&affiliateId='.$affiliateId.
'&operation='.$operation.
'&version='.$version.
'&keyword='.$text.
'&hits='.$hits.
'&sort='.$sort;
$str = file_get_contents($url);
$xml = simplexml_load_string($str);
$Items = $xml->xpath('//Items/Item');
$ret = '<div id="rakuten_item">';
foreach ($Items as $Item) {
$ret .= '<a href="' . $Item->affiliateUrl . '">';
$ret .= '<img src="' . $Item->mediumImageUrl . '" alt="' . $Item->itemName . '">';
$ret .= "</a>n";
}
$ret .= '</div>';
return $ret;
}
if (!empty($_REQUEST["keyword"])) {
$keyword = htmlspecialchars($_REQUEST["keyword"], ENT_QUOTES, 'UTF-8');
$limit = 10;
echo search_rakuten($keyword, $limit);
}
?>
<!-- Rakuten Web Services Attribution Snippet FROM HERE -->
<a href="http://webservice.rakuten.co.jp/" target="_blank">Supported by 楽天ウェブサービス</a>
<!-- Rakuten Web Services Attribution Snippet TO HERE -->
</body>
</html>
公開API活用ガイド (I・O BOOKS)
posted with amazlet at 12.01.24
ZAPA
工学社
売り上げランキング: 149253
工学社
売り上げランキング: 149253
関連エントリー
