百度
360搜索
搜狗搜索

php获取网页内容的四种方法详细介绍

  1. 使用xmlhttp对象,类似asp中的ActiveXObject对象

  代码:

//获取网页内容

$xhr = new COM("MSXML2.XMLHTTP");

$xhr->open("GET","http://localhost/xxx.php?id=2",false);

$xhr->send();

echo $xhr->responseText

  2. file_get_contents方法

$url = "http://www.aaaaaa.com";

$contents = file_get_contents($url);

//如果出现中文乱码使用下面代码

//$getcontent = iconv("gb2312", "utf-8",$contents);

echo $contents;

?>

  3. fopen->fread->fclose

$handle = fopen ("http://www.aaaaaa.com", "rb");

$contents = "";

do {

$data = fread($handle, 1024);

if (strlen($data) == 0) {

break;

}

$contents .= $data;

} while(true);

fclose ($handle);

echo $contents;

?>

  4. curl方法

$url = "http://www.aaaaaa.com";

$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扩展就可以了。

阅读更多 >>>  wordpress get_posts函数的使用方法 禁止输出指定类别的文章

文章数据信息:

本文主要探讨:"php获取网页内容的四种方法", 浏览人数已经达到41次, 首屏加载时间:1.405 秒。