使用php获取网页内容

1。使用xmlhttp对 象,类似于asp中的ActiveXObject对象,其实xmlhttp无非就是get和put的操作,在php里面

get的,直接用file_get_contents/fopen /readfile这些函数就是了

put的,自己写fsockopen发送也行,用NET_Curl也 行

(直接用系统函数要简单,通用,耗费资源少)

$xhr = new COM("MSXML2.XMLHTTP");
$xhr->open("GET","http://localhost/xxx.php?id=2",false);
$xhr->send();
echo $xhr->responseText

2。上面说的file_get_contents实现

<?php

$url = "http://www.jb51.net";
$contents = file_get_contents($url);

//如果出现中文乱码使用下面代码
//$getcontent = iconv("gb2312", "utf-8",$contents);
echo $contents;
?>

3.fopen->fread->fclose
PHP代码
[]CODE:
<?php
$handle = fopen ("http://www.jb51.net", "rb");
$contents = "";
do {
$data = fread($handle, 1024);
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($handle);
echo $contents;
?>

4.curl
PHP代码
[]CODE:
<?php
$url = "http://www.jb51.net";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//在需要用户检测的网页里需要增加下面两行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>

注:
1.使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini, 设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。
2.使用curl必须空间开 启curl。方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝 ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。

原文地址:https://www.cnblogs.com/danghuijian/p/4400359.html