2009-05-20 15:00

[PHP] 取得 URL 頁面上的 title 內容


<?php
/*
功能: 取得 URL 頁面上的 <title> 內容

參數:$_POST['url']
*/

// 設定最長執行的秒數
ini_set ("expect.timeout", 30);
set_time_limit(30);

// 檢查 URL
if(!isset($_POST['url']) || $_POST['url'] == ''){
echo "URL 錯誤";
exit;
}


/* 取得 URL 頁面資料 */
// 初始化 CURL
$ch = curl_init();

// 設定 URL
curl_setopt($ch, CURLOPT_URL, $_POST['url']);
// 讓 curl_exec() 獲取的信息以資料流的形式返回,而不是直接輸出。
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
// 在發起連接前等待的時間,如果設置為0,則不等待
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
// 設定 CURL 最長執行的秒數
curl_setopt ($ch, CURLOPT_TIMEOUT, 30);

// 嘗試取得文件內容
$store = curl_exec ($ch);


// 檢查文件是否正確取得
if (curl_errno($ch)){
echo "無法取得 URL 資料";
//echo curl_error($ch);/*顯示錯誤訊息*/
exit;
}

// 關閉 CURL
curl_close($ch);


// 解析 HTML 的 <head> 區段
preg_match("/<head.*>(.*)<\/head>/smUi",$store, $htmlHeaders);
if(!count($htmlHeaders)){
echo "無法解析資料中的 <head> 區段";
exit;
}

// 取得 <head> 中 meta 設定的編碼格式
if(preg_match("/<meta[^>]*http-equiv[^>]*charset=(.*)(\"|')/Ui",$htmlHeaders[1], $results)){
$charset = $results[1];
}else{
$charset = "None";
}

// 取得 <title> 中的文字
if(preg_match("/<title>(.*)<\/title>/Ui",$htmlHeaders[1], $htmlTitles)){
if(!count($htmlTitles)){
echo "無法解析 <title> 的內容";
exit;
}

// 將 <title> 的文字編碼格式轉成 UTF-8
if($charset == "None"){
$title=$htmlTitles[1];
}else{
$title=iconv($charset, "UTF-8", $htmlTitles[1]);
}
echo $title;
}

1 回應:

a-ming 提到...

好文章,感謝分享