各位大哥PHP高手,小弟我剛剛學PHP,在產生靜態分頁遇到了點問題,就是反頁的問題,希望可以給出一個漂亮完整的翻頁代碼,謝謝!
php產生靜態html分頁實現方法
$conn=mysql_connect('localhost','root','123456')
or die('串連失敗:'.mysql_error());
//選擇資料表
if (mysql_select_db('bbs',$conn))
{
echo'選擇資料庫成功!'.'
';
}
else
{
echo'資料庫選擇失敗!'.mysql_error().'
';
}
@header("Content-Type: text/html; charset=utf-8");
mysql_query("SET NAMES 'utf8'");
$fp = fopen ("moban/temp.html","r");
$content = fread ($fp,filesize ("moban/temp.html"));
$onepage =2;
$sql = "select id from message";
$query = mysql_query ($sql);
$num = mysql_num_rows ($query);
$allpages = ceil ($num / $onepage);
$filedir="news_1";
if (!is_dir($filedir)) {
//如果不存在就建立
mkdir($filedir,0777);
}
for ($i = 0;$i<$allpages; $i++){
if ($i == 0){
$indexpath = "$filedir/index.html";
} else {
$indexpath = "$filedir/index_".$i.".html";
}
$start = $i * $onepage;
$list = '';
$sql_for_page = "select * from message limit $start,$onepage";
$result=mysql_query($sql_for_page);
while($row=mysql_fetch_array($result))
{
$list .=$row['id']." ".$row['title'].'
'.$row['content'].'
';
}
$content1 = str_replace ("{ articletable }",$list.$i,$content);
//分頁
$list1 = '';
for ($j = 0;$j<$allpages; $j++){
if ($j == 0){
$list1 .= '第'.$j.'頁 |';
} else {
$list1 .= "第".$j."頁 |";
}
}
$content2 = str_replace("{ mune }",$list1,$content1);
if (is_file ($indexpath)){
@unlink ($indexpath); //若檔案已存在,則刪除
}
$handle = fopen ($indexpath,"w"); //開啟檔案指標,建立檔案
/*
檢查檔案是否被建立且可寫
*/
if (!is_writable ($indexpath)){
echo "檔案:".$indexpath."不可寫,請檢查其屬性後重試!"; //修改為echo
}
if (!fwrite ($handle,$content2)){ //將資訊寫入檔案
echo "組建檔案".$indexpath."失敗!"; //修改為echo
}
fclose ($handle); //關閉指標
}
fclose ($fp);die ("產生分頁檔案完成,如產生不完全,請檢查檔案許可權系統後重建!");
?>
------解決方案--------------------
/*
$fp=fopen("tmp.htm","r");//唯讀開啟模板
$str=fread($fp,filesize("tmp.htm"));//讀模數板中內容
//下一步將要替換的內容替換成要產生的內容
$str=str_replace("{title}",'新標題',$str);//將title替換成新標題
$str=str_replace("{content}",'新內容',$str);//將content替換成新內容
fclose($fp);//關閉檔案
$handle=fopen('news.htm',"w");//寫入方式開啟新聞路徑
fwrite($handle,$str);//把剛才替換的內容寫進產生HTM檔案
fclose($handle);
echo "產生成功";
*/
//批量產生
$row=array (array ("新聞標題","新聞內容"),array("新聞標題2","新聞內容2"));//二維數組
foreach($row as $id => $val){
$title=$val[0];
$content=$val[1];
$path=$id.'.htm';
$fp=fopen("tmp.htm","r");//唯讀開啟模板
$str=fread($fp,filesize("tmp.htm"));
//$str=file_get_contents("tmp.htm","r");