通過(guò)PHP獲取頁(yè)面title內(nèi)容的實(shí)戰(zhàn)演示:
范例代碼:
<?php
/*
功能: 取得 URL 頁(yè)面上的 <title> 內(nèi)容
參數(shù):$_POST['url']
*/
// 設(shè)置最長(zhǎng)執(zhí)行的秒數(shù)
ini_set ("expect.timeout", 30);
set_time_limit(30);
// 檢查 URL
if(!isset($_POST['url']) || $_POST['url'] == ''){
echo "URL 錯(cuò)誤";
exit;
}
/* 取得 URL 頁(yè)面數(shù)據(jù) */
// 初始化 CURL
$ch = curl_init();
// 設(shè)置 URL
curl_setopt($ch, CURLOPT_URL, $_POST['url']);
// 讓 curl_exec() 獲取的信息以數(shù)據(jù)流的形式返回,而不是直接輸出。
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
// 在發(fā)起連接前等待的時(shí)間,如果設(shè)置為0,則不等待
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
// 設(shè)置 CURL 最長(zhǎng)執(zhí)行的秒數(shù)
curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
// 嘗試取得文件內(nèi)容
$store = curl_exec ($ch);
// 檢查文件是否正確取得
if (curl_errno($ch)){
echo "無(wú)法取得 URL 數(shù)據(jù)";
//echo curl_error($ch);/*顯示錯(cuò)誤信息*/
exit;
}
// 關(guān)閉 CURL
curl_close($ch);
// 解析 HTML 的 <head> 區(qū)段
preg_match("/<head.*>(.*)<\/head>/smUi",$store, $htmlHeaders);
if(!count($htmlHeaders)){
echo "無(wú)法解析數(shù)據(jù)中的 <head> 區(qū)段";
exit;
}
// 取得 <head> 中 meta 設(shè)置的編碼格式
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 "無(wú)法解析 <title> 的內(nèi)容";
exit;
}
// 將 <title> 的文字編碼格式轉(zhuǎn)成 UTF-8
if($charset == "None"){
$title=$htmlTitles[1];
}else{
$title=iconv($charset, "UTF-8", $htmlTitles[1]);
}
echo $title;
}