php利用curl獲取網頁title內容
阿新 • • 發佈:2017-05-09
charset 釋放 tput head func reg 文字編碼 top titles
<?php $url = ‘http://www.k7wan.com‘; echo getTitle_web_curl($url); function getTitle_web_curl($url){ $title = ‘‘; $ch = curl_init(); //設置選項,包括URL curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); //執行並獲取HTML文檔內容 $output = curl_exec($ch); //釋放curl句柄 curl_close($ch); // 解析 HTML 的 <head> 區段 preg_match("/<head.*>(.*)<\/head>/smUi",$output, $htmlHeaders); if(!count($htmlHeaders)){ $title = "無法解析數據中的 <head> 區段"; } // 取得 <head> 中 meta 設置的編碼格式<meta charset="gb2312"> if(preg_match(‘/charset="(.*)"/‘,$htmlHeaders[1], $results)){ $charset = $results[1]; }else{ $charset = "None"; } // 取得 <title> 中的文字 if(preg_match("/<title>(.*)<\/title>/Ui",$htmlHeaders[1], $htmlTitles)){ if(!count($htmlTitles)){ $title = "無法解析 <title> 的內容"; exit; } // 將 <title> 的文字編碼格式轉成 UTF-8 if($charset == "None"){ $title=$htmlTitles[1]; }else{ $title=iconv($charset, "UTF-8", $htmlTitles[1]); } } return $title; }
php利用curl獲取網頁title內容