php自制工具函数,常用的函数集合

字符串与爬虫相关

1,截取

//截取有用的子串(爬虫相关)
//$info=网页  $first_key=开始的字符串  $last_key=结束的字符串
//return 中间的字符串;
function getKeyWord($info,$first_key,$last_key){
    $len = strlen($first_key);
    $first_key_start = strpos($info,$first_key);
    $last_key_start = strpos($info,$last_key,$first_key_start);
    $keyword = trim(substr($info,$first_key_start+$len,$last_key_start-$first_key_start-$len));
    return $keyword;
}

2,解析url

//$url :html链接
//return :解析后的html文档(字符串)
//获取CURL请求的输出信息,这个可以爬取https,非常好
function curl($url,$coding='utf-8') { 
    //初始化
    $ch = curl_init();
    //设置选项,包括url
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);//不返回response头部信息
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出。
   
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //支持重定向
    //不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $result = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
      //如果网站不是utf-8编码的话要转码
      if($coding!='utf-8'){
          $result= iconv($coding,"utf-8//IGNORE",$result);  
      }   
    return $result;   
}

猜你喜欢

转载自www.cnblogs.com/cl94/p/9020713.html