<?php
// Yahoo! JAPAN Search Services PHP Example Code Ver.1(2005/11/30)
//
$st_timer = microtime(true);
require './common.php';
$q = build_query();
// To cache, we save the result xml to a filename that is a
// hash of the query string. Note the use of tempnam() and
// rename() to make sure the file is created atomically.
$cache_file = '/tmp/yws_'.md5($service[$_REQUEST['type']].$q);
/*ホスティングしているサーバーの多くは「PHPセーフモード」を有効にしているため
ファイルを作成できない場合があります。
そのため、
$cache_file = dirname ($_SERVER['SCRIPT_FILENAME']) . '/yws_'.md5($service[$_REQUEST['type']].$q);
のように、キャッシュファイルを作成するディレクトリを変更する必要があるかもしれません。
上記の場合、カレントディレクトリのアクセス権を0x777(書き込み許可)にする必要があるでしょう。*/
if(file_exists($cache_file) && filemtime($cache_file) > (time()-7200)) {
/* キャッシュファイルが存在する場合 */
$raw = file_get_contents($cache_file);
/* キャッシュファイルの内容をロードする*/
} else {
/*キャッシュファイルが存在しないので、クエリーに応じたキャッシュを作成する*/
$raw = file_get_contents($service[$_REQUEST['type']].$q);
$tmpf = tempnam('/tmp','YWS');
/*上記のセーフモードと同様です*/
file_put_contents($tmpf, $raw);
/*ファイルに書き出す*/
rename($tmpf, $cache_file);
/*PHPセーフモードにひっかかる可能性があります
chmod($tmpf,0777);
copy($tmpf,$cache_file);
unlink($tmpf);
のような姑息な手段が必要かもしれません。*/
}
/*以下、SimpleXMLを利用する点はサンプル4.と同じです*/
$xml = simplexml_load_string($raw);
// Load up the root element attributes
foreach($xml->attributes() as $name=>$attr) $res[$name]=$attr;
$first = $res['firstResultPosition'];
$last = $first + $res['totalResultsReturned']-1;
echo "<p>Matched ${res[totalResultsAvailable]}, showing $first to $last</p>\n";
if(!empty($res['ResultSetMapUrl'])) {
echo "<p>Result Set Map: <a href=\"${res[ResultSetMapUrl]}\">${res[ResultSetMapUrl]}</a></p>\n";
}
for($i=0; $i<$res['totalResultsReturned']; $i++) {
foreach($xml->Result[$i] as $key=>$value) {
switch($key) {
case 'Thumbnail':
echo "<img src=\"{$value->Url}\" height=\"{$value->Height}\" width=\"{$value->Width}\" />\n";
break;
case 'Cache':
echo "Cache: <a href=\"{$value->Url}\">{$value->Url}</a> [{$value->Size}]<br />\n";
break;
case 'PublishDate':
case 'ModificationDate':
echo "<b>$key:</b> ".strftime('%X %x',$value)."<br />\n";
/*ファイルに書き出した時に、日付がシリアル値になる場合があります。
その場合、数値なので、strftimeでは解析できずにエラーが発生します。
strftimeの部分を、date("H:i:s Y/m/d",$value)のようにする必要があるかもしれません。*/
break;
default:
if(stristr($key,'url')) echo "<a href=\"$value\">$value</a><br />\n";
else echo "<b>$key:</b> $value<br />";
break;
}
}
echo "<hr />\n";
}
next_prev($res, $first, $last);
echo "<br /><br />Page generated in <b>".(microtime(true)-$st_timer)."</b> seconds<br />\n";
done();
?>
|