我用file_get_contents("$url");打不开服务器上本地项目中的网页
后来我试试外网,发现file_get_contents("www.baidu.com"),这样可以很奇怪了,不知道为什么本地的不行,外网的可以,本地的报错:Warning: file_get_contents(http://localhost:8070/index.php/%E4%BD%BF%E7%94%A8%E5%B8%AE%E5%8A%A9) [function.file-get-contents]: failed to open stream: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 in C:\wamp\www\test.php on line 3
是不是apache的配置问题,还是什么的?禁止打开吗?项目是可以浏览的,file_get_contents打不开。
后来我试试外网,发现file_get_contents("www.baidu.com"),这样可以很奇怪了,不知道为什么本地的不行,外网的可以,本地的报错:Warning: file_get_contents(http://localhost:8070/index.php/%E4%BD%BF%E7%94%A8%E5%B8%AE%E5%8A%A9) [function.file-get-contents]: failed to open stream: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 in C:\wamp\www\test.php on line 3
是不是apache的配置问题,还是什么的?禁止打开吗?项目是可以浏览的,file_get_contents打不开。
2、将localhost 修改为127.0.0.1试试
3、file_get_contents("www.baidu.com")最修改为file_get_contents("http://www.baidu.com")
另外建议
在抓取网络内容时建议不要使用file_get_contents,因为它效率比较低。
使用curl实现更高效一些
实现方法:/**
* Send a GET requst using cURL
* @param string $url to request
* @param array $get values to send
* @param array $options for cURL
* @return string
*/
function curl_get($url, array $get = NULL, array $options = array()) {
$defaults = array(
CURLOPT_URL => $url . (strpos($url, '?') === FALSE ? '?' : '') . http_build_query($get),
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 4
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if (!$result = curl_exec($ch)) {
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
$get = array('wd'=>'php');
$html = curl_get("http://www.baidu.com/s?",$get);
echo "<textarea cols='80' rows='20' >{$html}</textarea>";
哦哦,是urlencode的。你看看httpd.conf,你的服务端bind在什么IP上。
http://localhost:8070/index.php/%E4%BD%BF%E7%94%A8%E5%B8%AE%E5%8A%A9能直接打开
就是file_get_contents().这里由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败..
不用localhost,用域名也可以打开.
www.baidu.com是我简写了,外网是可以打开的,就是本地的不行,应该是wamp的配置问题吧?
echo ini_get('allow_url_fopen');