《PHP實例:PHP中使用CURL獲取頁面title例子》要點(diǎn):
本文介紹了PHP實例:PHP中使用CURL獲取頁面title例子,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP教程通過PHP獲取頁面title內(nèi)容的實戰(zhàn)演示:
PHP教程范例代碼:
代碼如下:
<?php??
/*?
功能: 取得 URL 頁面上的 <title> 內(nèi)容??
?
參數(shù):$_POST['url']?
*/??
??
// 設(shè)置最長執(zhí)行的秒數(shù)??
ini_set ("expect.timeout", 30);??
set_time_limit(30);??
??
// 檢查 URL??
if(!isset($_POST['url']) || $_POST['url'] == ''){???
?? echo "URL 錯誤";??
?? exit;??
}??
??
??
/* 取得 URL 頁面數(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è)置為0,則不等待??
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);??
// 設(shè)置 CURL 最長執(zhí)行的秒數(shù)??
curl_setopt ($ch, CURLOPT_TIMEOUT, 30);??
??
// 嘗試取得文件內(nèi)容??
$store = curl_exec ($ch);??
??
??
// 檢查文件是否正確取得??
if (curl_errno($ch)){??
?? echo "無法取得 URL 數(shù)據(jù)";??
?? //echo curl_error($ch);/*顯示錯誤信息*/??
?? exit;??
}??
??
// 關(guān)閉 CURL??
curl_close($ch);??
??
??
// 解析 HTML 的 <head> 區(qū)段??
preg_match("/<head.*>(.*)<\/head>/smUi",$store, $htmlHeaders);??
if(!count($htmlHeaders)){??
?? echo "無法解析數(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 "無法解析 <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;??
}??
歡迎參與《PHP實例:PHP中使用CURL獲取頁面title例子》討論,分享您的想法,維易PHP學(xué)院為您提供專業(yè)教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/12808.html