2009-05-20 15:00

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

  1. <?php 
  2. /* 
  3. 功能: 取得 URL 頁面上的 <title> 內容  
  4.  
  5. 參數:$_POST['url'] 
  6. */ 
  7.  
  8. // 設定最長執行的秒數 
  9. ini_set ("expect.timeout", 30); 
  10. set_time_limit(30); 
  11.  
  12. // 檢查 URL 
  13. if(!isset($_POST['url']) || $_POST['url'] == ''){  
  14.    echo "URL 錯誤"; 
  15.    exit; 
  16. } 
  17.  
  18.  
  19. /* 取得 URL 頁面資料 */ 
  20. // 初始化 CURL 
  21. $ch = curl_init(); 
  22.  
  23. // 設定 URL  
  24. curl_setopt($ch, CURLOPT_URL, $_POST['url']);  
  25. // 讓 curl_exec() 獲取的信息以資料流的形式返回,而不是直接輸出。 
  26. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  27. // 在發起連接前等待的時間,如果設置為0,則不等待 
  28. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0); 
  29. // 設定 CURL 最長執行的秒數 
  30. curl_setopt ($ch, CURLOPT_TIMEOUT, 30); 
  31.  
  32. // 嘗試取得文件內容 
  33. $store = curl_exec ($ch); 
  34.  
  35.  
  36. // 檢查文件是否正確取得 
  37. if (curl_errno($ch)){ 
  38.    echo "無法取得 URL 資料"; 
  39.    //echo curl_error($ch);/*顯示錯誤訊息*/ 
  40.    exit; 
  41. } 
  42.  
  43. // 關閉 CURL 
  44. curl_close($ch); 
  45.  
  46.  
  47. // 解析 HTML 的 <head> 區段 
  48. preg_match("/<head.*>(.*)<\/head>/smUi",$store, $htmlHeaders); 
  49. if(!count($htmlHeaders)){ 
  50.    echo "無法解析資料中的 <head> 區段"; 
  51.    exit; 
  52. }     
  53.  
  54. // 取得 <head> 中 meta 設定的編碼格式 
  55. if(preg_match("/<meta[^>]*http-equiv[^>]*charset=(.*)(\"|')/Ui",$htmlHeaders[1], $results)){ 
  56.    $charset =  $results[1]; 
  57. }else{  
  58.    $charset = "None"; 
  59. } 
  60.  
  61. // 取得 <title> 中的文字  
  62. if(preg_match("/<title>(.*)<\/title>/Ui",$htmlHeaders[1], $htmlTitles)){ 
  63.    if(!count($htmlTitles)){ 
  64.        echo "無法解析 <title> 的內容"; 
  65.        exit; 
  66.    } 
  67.  
  68.    // 將  <title> 的文字編碼格式轉成 UTF-8 
  69.    if($charset == "None"){ 
  70.        $title=$htmlTitles[1]; 
  71.    }else{ 
  72.        $title=iconv($charset, "UTF-8", $htmlTitles[1]); 
  73.    } 
  74.    echo $title; 
  75. } 

1 回應:

a-ming 提到...

好文章,感謝分享