
PHP获取网页内容的几种方法
方法1:用file_get_contents以get方式获取内容。
方法2:用file_get_contents函数,以post方式获取url。
'bar');
$data= http_build_query($data);
$opts= array(
'http'=> array(
'method'=> 'POST',
'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content'=> $data
)
);
$ctx= stream_context_create($opts);
$html= @file_get_contents($url,'',$ctx);如果需要再传递cookie数据,则把
立即学习“PHP免费学习笔记(深入)”;
'header'=>"Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
修改为
'header'=>"Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " .strlen($data) . "\r\n". "cookie:cookie1=c1;cookie2=c2\r\n";
即可。
方法3:用fopen打开url,以get方式获取内容。
": echo"url body: $result"; fclose($fp); ?>
相关推荐:《PHP入门教程》
方法4:用fopen打开url,以post方式获取内容。
'bar2','foo3'=>'bar3');
$data= http_build_query($data);
$opts= array(
'http'=> array(
'method'=> 'POST',
'header'=>"Content-type: application/x-www-form-urlencoded\r\nCookie:cook1=c3;cook2=c4\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content'=> $data
)
);
$context= stream_context_create($opts);
$html= fopen('http://www.test.com/zzzz.php?id=i3&id2=i4','rb',false, $context);
$w=fread($html,1024);
echo$w;
?>方法5:用fsockopen函数打开url,以get方式获取完整的数据,包括header和body。
方法6:用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body。
$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);
// Find out which port is needed - if not given use standard (=80)
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;
// building POST-request:
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
$request.="Host: ".$URL_Info["host"]."\n";
$request.="Referer: $referer\n";
$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: close\n";
$request.="Cookie: $cookie\n";
$request.="\n";
$request.=$data_string."\n";
$fp= fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp,$request);
while(!feof($fp)) {
$result.= fgets($fp, 1024);
}
fclose($fp);
return$result;
}
?>方法7:使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展。
HMCSS是由河马工作室全新开发的通用的企业网站系统,是PHP+MYSQL的架构,采用DIV+CSS的方式进行网页布局,网站的功能包括有:企业简介,图片展示幻灯,产品图片滚动,企业荣誉,实力展示,产品分类及展示,网上招聘,在线留言,联系我们,在线地图等内容,另外还带有完整的管理后台,如网站SEO优化关键词等都可以自由设定。 HMCSS目前发布的是1.0版本,就是上述的这些内容。后面我们还要加上产品
这里收集了3种利用php获得网页源代码抓取网页内容的方法,我们可以根据实际需要选用。
1、使用file_get_contents获得网页源代码
这个方法最常用,只需要两行代码即可,非常简单方便。
参考代码:
2、使用fopen获得网页源代码
这个方法用的人也不少,不过代码有点多。
参考代码:
3、使用curl获得网页源代码
使用curl获得网页源代码的做法,往往是需要更高要求的人使用,例如当你需要在抓取网页内容的同时,得到网页header信息,还有ENCODING编码的使用,USERAGENT的使用等等。
参考代码一:
参考代码二:










