Home >Backend Development >PHP Tutorial >Four ways to get web content in php
This article introduces four methods to obtain web content using PHP, including xmlhttp method, file_get_contents method, fopen method, and curl method. Friends in need can refer to it.
1. Use xmlhttp object, similar to ActiveXObject object in asp. Code: <?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 method <?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 method <?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; ?> Note: 1. When using file_get_contents and fopen, allow_url_fopen must be enabled. Method: Edit php.ini and set allow_url_fopen = On. When allow_url_fopen is turned off, neither fopen nor file_get_contents can open remote files. 2. For the curl method, you need to enable curl. Method: Modify php.ini under Windows, remove the semicolon in front of extension=php_curl.dll, and copy ssleay32.dll and libeay32.dll to C:/WINDOWS/system32; Just install the curl extension under Linux. |