PHP中使用CURL擷取頁面title例子,curltitle_PHP教程

來源:互聯網
上載者:User

PHP中使用CURL擷取頁面title例子,curltitle


通過PHP擷取頁面title內容的實戰示範:

範例代碼:

複製代碼 代碼如下:
<?php
/*
功能: 取得 URL 頁面上的 內容

參數:$_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 的 區段
preg_match("/(.*)<\/head>/smUi",$store, $htmlHeaders);
if(!count($htmlHeaders)){
echo "無法解析資料中的 區段";
exit;
}

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

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

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

http://www.bkjia.com/PHPjc/939415.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/939415.htmlTechArticlePHP中使用CURL擷取頁面title例子,curltitle 通過PHP擷取頁面title內容的實戰示範: 範例代碼: 複製代碼 代碼如下: php /* 功能: 取得 URL 頁面上...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.