发布网友 发布时间:2022-04-24 18:18
共3个回答
懂视网 时间:2022-04-28 10:57
php中抓取网页内容的实例详解
方法一:
使用file_get_contents
方法实现
$url = "http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml"; $html = file_get_contents($url); //如果出现中文乱码使用下面代码 //$getcontent = iconv("gb2312", "utf-8",$html); echo "<textarea style='width:800px;height:600px;'>".$html."</textarea>";
代码很简单,一看就懂,不解释了。
方法二:
使用curl实现
$url = "http://news.sina.com.cn/c/nd/2016-10-23/doc-ifxwztru6951143.shtml"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $html = curl_exec($ch); curl_close($ch); echo "<textarea style='width:800px;height:600px;'>".$html."</textarea>";
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
加上这句代码,表示如果请求被重定向时,可以访问到最终的请求页面,不然请求的结果会显示如下内容:
相关学习推荐:php编程(视频)
热心网友 时间:2022-04-28 08:05
1.file_get_contents
PHP代码
复制代码 代码如下:
<?php
$url = "http://www.jb51.net";
$contents = file_get_contents($url);
//如果出现中文乱码使用下面代码
//$getcontent = iconv("gb2312", "utf-8",$contents);
echo $contents;
?>
2.curl
PHP代码
复制代码 代码如下:
<?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;
?>
3.fopen->fread->fclose
PHP代码
复制代码 代码如下:
<?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;
?>
注:
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扩
展。
热心网友 时间:2022-04-28 09:23
使用 file_get_contents、fopen等函数
这里介绍一下 file_get_contents
file_get_contents(path,include_path,context,start,max_length)
参数描述
path 必需。规定要读取的文件。
include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。
context 可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 null,则忽略。
start 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。
max_length 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。
<?php
echo file_get_contents("test.txt");
?>
也可以使网址
<?php
echo file_get_contents(".com");
?>
非常好用 还可以设置访问超时等等
希望对你有帮助