PHP正則匹配Html內容,並通過瀏覽器彈框下載Excel
一、我結合之前自己寫的2篇,寫了這一篇
PHP打印Excel表格並下載 去看看
PHP正則匹配html標籤 去看看
二、瀏覽器輸入地址,訪問,彈出Excel下載框
三、下載完成後Excel的內容
四、完整代碼
<?php
namespace app\index\controller;
class Ablog extends Base
{
/**
* 開始方法
*/
public function start(){
$data = $this->getData();
$this->downExcel($data);
}
/**
* 瀏覽器彈框下載Excel
* @param $data 存放到表格中的數據
*/
public function downExcel($data){
//打開請求頭
$filename = "博文信息(".date("Ymd").")";
//設置瀏覽器信息
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header("Content-Disposition:filename=".$filename.".xls");
ob_clean(); //清空緩衝區
echo '<meta http-equiv="Content-Type" content="text/html; charset=GBK" />';
$content = '<table border="1" cellspacing="0">'; // width="70%"
$content .='<tr >';//style="font-size: 16px;font-weight: 800;"
$content .='<th align="center" height="30" width="120">'.mb_convert_encoding("類型",'GBK').'</th>';
$content .='<th align="center" height="30" width="120">'.mb_convert_encoding("標題",'GBK').'</th>';
$content .='</tr>';
foreach ($data as $k => $v){
$content .='<tr>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['type'],'GBK').'</td>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['title'],'GBK').'</td>';
$content .='</tr>';
}
$content .='</table>';
echo $content;
exit();
}
//正則匹配html中的數據
public function getData(){
$url = "https://blog.csdn.net/cungudafa";
$html = file_get_contents($url);
//匹配是原創還是轉載,匹配標題
$pattern = '/<span class="article-type type-1 float-none">([^\<]+)<\/span>([^\<]+)<\/a>/';
preg_match_all($pattern, $html, $result);
if (empty($result[0])){
exit('匹配內容失敗!');
}
//每一個()對應一個數組,默認第0個是匹配所有內容,所以匹配的結果裏有3個數組
// $allHtml = $result[0];
// var_export($allHtml);die(); //打印看下效果
//$allType 和 $allTitle 數量一致
$allType = $result[1];
$allTitle = $result[2];
//處理數據
$data = [];
foreach ($allType as $key => $value){
$data[] = [
'type' => $value,
'title' => trim($allTitle[$key]) //獲取標題,去除空格
];
}
return $data;
}
}