当前位置: 首页 > 图灵资讯 > 技术篇> PHP 获取网页内容的三种方法

PHP 获取网页内容的三种方法

来源:图灵教育
时间:2023-06-27 15:08:11

你想要的内容是通过正则表达式过滤获得的。

file_get_contents() 在字符串中读取整个文件。

<meta charset="utf-8">  <?图灵 $url = "http://onestopweb.iteye.com/"; $contents = file_get_contents($url); //如果有中文乱码,请使用以下代码 //$getcontent = iconv(gb2312) "utf-8",$contents); echo $contents; ?>

curl_init() 新会话初始化,curl句柄返回curl_setopt(), curl_exec()和curl_close() 函数使用。

<meta charset="utf-8">  <?图灵 $url = "http://onestopweb.iteye.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; ?>

fopen->fread->fclose fopen()文件流 打开文件或函数 URL。fread() 函数读取文件。fclose() 打开文件关闭函数。

<meta charset="utf-8">  <?图灵 $handle = fopen ("http://onestopweb.iteye.com/", "rb"); $contents = ""; do { $data = fread($handle, 1024); if (strlen($data) == 0) { break; } $contents .= $data; } while(true); fclose ($handle); echo $contents; ?>

PS:1.使用file_get_contents和fopen必须有打开allow的空间url_fopen。方法:编辑图灵.ini,设置alllow__url_fopen = On,allow_urlfopen关闭时,fopen和file_get_contents无法打开远程文件。 2.使用curl必须打开curl的空间。方法:在windows下修改图灵.ini,extension=图灵_curl.去掉dll前的分号,需要复制ssleay32.ldll和libeay32.dll到 C:\Windows\system 或者 C:\Windows\System32。

如图:

PHP 获取网页内容的三种方法_file_get_contents()

我的系统是WIN7的64位,在这个文件夹中放置两个dll文件是有效的。

PHP 获取网页内容的三种方法_图灵_02