Heim  >  Artikel  >  Backend-Entwicklung  >  php 获取网页内容的四种方法

php 获取网页内容的四种方法

WBOY
WBOYOriginal
2016-07-25 08:56:461116Durchsuche
本文介绍下,用php获取网页内容的四种方法,包括xmlhttp方法、file_get_contents方法、fopen方法、curl方法。有需要的朋友参考下。

1,使用xmlhttp对象,类似asp中的ActiveXObject对象。 代码:

<?php
//获取网页内容
$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://bbs.it-home.org"; 
$contents = file_get_contents($url);

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

3,fopen->fread->fclose

<?php 
$handle = fopen ("http://bbs.it-home.org", "rb"); 
$contents = ""; 
do { 
$data = fread($handle, 1024); 
if (strlen($data) == 0) { 
break; 
} 
$contents .= $data; 
} while(true); 
fclose ($handle); 
echo $contents; 
?>

4,curl方法

<?php 
$url = "http://bbs.it-home.org"; 
$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扩展就可以了。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn