Home  >  Article  >  php教程  >  PHP之抓取网页数据

PHP之抓取网页数据

WBOY
WBOYOriginal
2016-06-06 20:01:34858browse

最近在公司开发一项目、配合客户端人员开发接口,接口中需要接受客户端人员传递过来的头部信息,所以在浏览器中访问这个接口就无法访问、因为你传递的参数不全,最近想了一个方法:那就是在本地模拟一些数据提交,这个时候本人用到的是fsockopen函数,这个函

        最近在公司开发一项目、配合客户端人员开发接口,接口中需要接受客户端人员传递过来的头部信息,所以在浏览器中访问这个接口就无法访问、因为你传递的参数不全,最近想了一个方法:那就是在本地模拟一些数据提交,这个时候本人用到的是fsockopen函数,这个函数挺不错的。。




       function index(){
		
		$posturl = "XXX";
		$Did = '352110051958276';
		$Key = md5($Did.$this->Keym);
		$ms = $this->require_by_socket("Mm","action",$posturl,$Did,$Key);
		//$this->display();
		echo  $ms;
	}
	function require_by_socket($action,$method,$posturl,$Did,$Key) {
		
		$fp = fsockopen ( "$posturl", 80, $errno, $errstr, 30 );
		if (! $fp) {
			echo "$errstr ($errno)<br>\n";
		} else {
			
			//$params = array ('did' => 1009, 'ver' => '199/9/201208','filmid' => 18 );
			//$post = http_build_query($params);
			$post = "did=352110051958276&ver=199/22/20121222&filmid=18&model=HTC&os=and&pid=1&refresh=1";
			//echo $post;exit;
			$header = "POST /service/index.php/$action/$method HTTP/1.1\r\n";
			$header .= "Host: $posturl\r\n";
			$header .= "Content-Type:application/x-www-form-urlencoded" . "\r\n";
			$header .= "Content-Length: " . strlen ( $post ) . "\r\n";
			$header .="Did:$Did\r\n";
			$header .="Key:$Key\r\n";                      //这里就是 提交header头部信息
			$header .= "Connection: Close\r\n\r\n";
			$header .= $post."\r\n";	
			$inheader = 1;
			fputs ( $fp, $header );
			while ( ! feof ( $fp ) ) {
				
				$result = fgets ( $fp, 1024 ); //去除请求包的头只显示页面的返回数据
				if ($inheader && ($result == "\n" || $result == "\r\n")) {
					$inheader = 0;
				}
				//echo $inheader;exit;
				if ($inheader == 0) {
					$info .= $result;
				}
			}
			fclose ( $fp );
			return $info;
			
			
		}
	}

备注:以上
$header .="Did:$Did\r\n";
$header .="Key:$Key\r\n"; 

这些参数其实就是提交开发者想要的头部参数信息,然后您可以通过函数处理这样参数 就可以获取您想要的。





还分享下另外的一种方式:


CURL:

 

<strong><span><?php function curlGetData($url,$header)
{
	$ch = curl_init() or die (curl_error());
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);    //设置http头   
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$data=curl_exec($ch) or die (curl_error());
	curl_close($ch);
	return $data;	
}
$header[]='Pid:1';
$header[]='Ver:100/26/200000';
$header[]='Key:'.xxxxx;
$header[]='Did:test';

$url="http://xxxx.com/Yxx/xxxx?id=65761723&type=12&";
echo curlGetData($url,$header);</span></span></strong>







Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Web图片优化总结Next article:读取磁盘文件 删除