欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP中使用CURL获取页面title例子

程序员文章站 2022-12-22 22:14:45
通过php获取页面title内容的实战演示: 范例代码: 复制代码 代码如下:

通过php获取页面title内容的实战演示:

范例代码:

复制代码 代码如下:

<?php  
/* 
功能: 取得 url 页面上的 <title> 内容  
 
参数:$_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 的 <head> 区段  
preg_match("/<head.*>(.*)<\/head>/smui",$store, $htmlheaders);  
if(!count($htmlheaders)){  
   echo "无法解析数据中的 <head> 区段";  
   exit;  
}      
     
// 取得 <head> 中 meta 设置的编码格式  
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> 的内容";  
       exit;  
   }  
     
   // 将  <title> 的文字编码格式转成 utf-8  
   if($charset == "none"){  
       $title=$htmltitles[1];  
   }else{  
       $title=iconv($charset, "utf-8", $htmltitles[1]);  
   }  
   echo $title;  
}