隨機顯示的版本咱們在上一篇文章中作了,如今讓咱們來作一個搜索版本吧,哈哈哈哈哈哈,也是一個簡單的dome,須要大家本身美化,固然這個版本也很簡單,有能力的本身優化程序和添加分頁功能(本博主能力有限啊,歡迎有興趣的兄弟,評論區給出建議)php
本次程序就3個文件,以下圖:html
其中index.php就是一個簡單的搜索框頁面,taobao.dat文件我就不說了,上篇文章裏面有提到,taobao.php文件就是根據index.php搜索框中的搜索關鍵詞來處理的文件。web
不說了,上代碼數據庫
index.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>搜索顯示淘寶天貓優惠券dome</title> </head> <body> <form class="navbar-form navbar-left" action="taobao.php" method="post"> <div class="form-group"> <input type="text" name="key" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">搜索</button> </form> </body> </html>
taobao.php文件代碼以下:dom
<?php ini_set("error_reporting","E_ALL & ~E_NOTICE"); function webalert($Key){ $html="<script>\r\n"; $html.="alert('".$Key."');\r\n"; $html.="history.go(-1);\r\n"; $html.="</script>"; exit($html); } function charaget($data){ if(!empty($data) ){ $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ; if( $fileType != 'UTF-8'){ $data = mb_convert_encoding($data ,'UTF-8' , $fileType); } } return $data; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $trimmed = array_map('trim', $_POST); $key=$trimmed['key']; if(empty($key)) { webalert('親,您確認下輸入!'); } $keyword = explode(" ", $key); //拆分關鍵字爲數組 $keycount = count($keyword); //統計關鍵字個數 $files = "taobao.dat"; $filer = fopen($files, "r") or webalert('沒法打開文件!'); while (!feof($filer)) {//檢測是否已到達文件末尾 $row = fgets($filer);//從文件指針中讀取一行 $rows = trim(charaget($row));//轉UTF-8,並移除字符串兩側的空白字符或其餘預約義字符 //var_dump($rows); if ($rows) { $e_rows = explode("\t", $rows); $a++; //給數據編行號 $b=0; //初始化關鍵字,比對次數 $tmp_str=""; //echo "$a===$e_rows[0]==$key == <br>\r\n"; foreach($keyword as $val){ if (strstr( $e_rows[0] , $val ) !== false ){ //搜索框中的關鍵字和數據庫中的標題匹配 //echo "$a <br>\r\n"; $b++; if ($b == $keycount) {//篩選出多個關鍵字出如今同一個標題中 $tmp_str=$a; if($tmp_str!="" && !empty($tmp_str)){ $c++;//篩選後,查詢結果進行編號 echo " <table> <tbody> <tr> <td>查詢結果 $c </td> <td>$e_rows[0]</td> <td><img src=\"$e_rows[1]\" width=\"100\" /></td> <td><a href=\"$e_rows[2]\">購買連接</a></td> <td>商品價格(單位:元):$e_rows[3]</td> <td>商品月銷量:$e_rows[4]</td> <td>平臺類型:$e_rows[5]</td> <td>優惠券面額:$e_rows[6]</td> <td>優惠券結束時間:$e_rows[7]</td> <td><a href=\"$e_rows[8]\">先領優惠券</a></td> </tr></tbody></table>"; } } } } } } //echo "$c"; if ($c < 1) { echo '<table cellspacing="0"><tr>'; echo "<td colspan=2>沒有查詢到相關信息哦。<br>"; echo "<strong>可能緣由及建議:</strong><br>"; echo "1. 若是沒有結果請嘗試減小或更換查詢關鍵詞。<br>"; echo "2. 多關鍵詞用空格隔開,參考:毛衣 加厚 男。<br>"; echo "3. 只涵蓋部分類目:有些類目的商品查詢不到。</td>"; echo '</tr></table>'; } else { } fclose($filer); } ?>