本小节的名称为 fsockopen,curl与file_get_contents,具体是探讨这三种方式进行网络数据输入输出的一些汇总。关于 fsockopen 前面已经谈了不少,下面开始转入其它。这里先简单罗列一下一些常见的抓取网络数据的一些方法。
1. 用 file_get_contents 以 get 方式获取内容:
13 else {
14 $request = "GET $query HTTP/1.1\r\n";
15 $request .= "Host: $url[host]\r\n";
16 $request .= "Connection: Close\r\n";
17 if($cookie) $request.="Cookie: $cookie\n";
18 $request.="\r\n";
19 fwrite($fp,$request);
20 $result = '';
21 while(!feof($fp))
22 {
23 $result .= @fgets($fp, 1024);
24 }
25 fclose($fp);
26 return $result;
27 }
28 }
29 //获取url的html部分,去掉header
30 function GetUrlHTML($url,$cookie=false)
31 {
32 $rowdata = get_url($url,$cookie);
33 if($rowdata)
34 {
35 $body= stristr($rowdata,"\r\n\r\n");
36 $body=substr($body,4,strlen($body));
37 return $body;
38 }
39
40 return false;
41 }
42
43 echo get_url($url);
44
45 echo GetUrlHTML($url);
程序输出:
01 Query:/php/sock.php?site=xxx.netHTTP/1.1 200 OK
02 Date: Wed, 19 Feb 2014 06:06:25 GMT
03 Server: Apache/2.2.3 (CentOS)
04 X-Powered-By: PHP/5.3.3
05 Vary: Accept-Encoding
06 Content-Length: 21
07 Connection: close
08 Content-Type: text/html; charset=UTF-8
09
10 Welcome to NowaMagic
13 // making string from $data
14 foreach($data as $key=> $value)
15 $values[]="$key=".url www.hbbz08.com encode($value);
16 $data_string=implode("&",$values);
17
18 // Find out which port is needed - if not given use standard (=80)
19 if(!isset($URL_Info["port"]))
20 $URL_Info["port"]=80;
21
22 $request = '';
23 // building POST-request:
24 $request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
25 $request.="Host: ".$URL_Info["host"]."\n";