Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

PHP5 の SimpleXML を使ってみる

遅ればせながら PHP5 で遊んでみる。オブジェクト指向のなんとかゆのはよくわかんないので、とりあえず、新たに標準でバンドルされることとなった SQLite, SimpleXML, SOAP の目玉 3 機能のうち、SimpleXML を使って Amazon Web Service を通して商品を検索するスクリプトを書いてみることに(非常につまらないものですが、まぁ練習なので…)。ほんとは SOAP 使いたかったけど、どうやってもうまくいかなかったので、REST API にリクエストを投げて返ってきた XML を SimpleXML でごにょる感じにしました。つーか、超簡単。返ってきた XML から以下のようにして XML オブジェクトを作成し、あとは foreach かなんかでまわしつつ内容を表示させるだけ。

$xml = simplexml_load_string($response);

んで、以下の通り超テケトーにフォームを作ったりしたら、なんとなくそれっぽい感じになるにはなって、これはなんというか簡単かつ手軽なので素晴らし過ぎています!

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP5 によるアマゾン・ウェブ・サービスのテスト</title>
<style>
<!--
  .AmazonImageSmall{float:left; width:60px; margin-right:100px;}
  dt{margin:1em 0;}
    • >
</style> </head> <body> <h1>PHP5 によるアマゾン・ウェブ・サービスのテスト</h1> <form action="" method="get"> <input type="text" name="keyword" value="" size="50" /> <input type="submit" value=送信" /> </form> <?php if ($_GET['keyword']) { $keyword = htmlspecialchars($_GET['keyword']); $keyword = mb_convert_encoding($keyword, "utf-8", "auto"); print("<hr />\n<p>$keywordの検索結果は以下の通り。</p>\n"); $request_name = "BlendedSearch"; $associates_id = "アソシエイト ID"; $type = "lite"; $dev_token = "デヴェロッパーズ・トークン"; $locale = "jp"; $amazon_rest_api = "http://xml.amazon.co.jp/onca/xml3"; include_once("HTTP/Request.php"); $request =& new HTTP_Request($amazon_rest_api); $request->setMethod(HTTP_REQUEST_METHOD_GET); $request->addQueryString($request_name, $keyword); $request->addQueryString("t", $associates_id); $request->addQueryString("type", $type); $request->addQueryString("dev-t", $dev_token); $request->addQueryString("locale", $locale); $request->addQueryString("f", "xml"); $request->sendRequest(); $response = $request->getResponseBody(); $xml = simplexml_load_string($response); foreach ($xml->ProductLine as $product) { print("<h2>$product->Mode</h2>\n"); foreach ($product->ProductInfo->Details as $product_details) { print <<< EOS <dl> <dt><a href="http://www.amazon.co.jp/exec/obidos/ASIN/$product_details->Asin/$associates_id/ref=nosim">$product_details->ProductName</a></dt> <dd class="AmazonImageSmall"><img src="$product_details->ImageUrlSmall" alt="$product_details->ProductName" onload="if(this.width=='1') this.src='./no_image_avallable.gif';" /></dd> <dd>$product_details->Catalog</dd> <dd>$product_details->Manufacturer</dd> <dd>$product_details->OurPrice</dd> <dd>$product_details->ReleaseDate</dd> </dl> EOS; } } } ?> <address> けんたろ / kentaro [<a href="mailto:webmaster@antipop.zapto.org" title="管理人へメール">webmaster@antipop.zapto.org</a>] </address> </body> </html>

今回は手始めに SimpleXML を試してみましたが、今度は SOAP とか使いたいなぁ。なにに使えばいいのかわかんないけど。ともあれ、PHP5 の正式リリースが待ち遠しい!!!