PHP file_get_contents()不起作用

Kri*_*ury 4 php codepad

任何人都可以解释为什么以下代码返回警告:

<?php
  echo file_get_contents("http://google.com");
?>
Run Code Online (Sandbox Code Playgroud)

我收到警告:

Warning: file_get_contents(http://google.com): 
failed to open stream: No such file or directory on line 2
Run Code Online (Sandbox Code Playgroud)

请参阅键盘

Sud*_*oti 11

作为替代方案,您可以使用cURL,例如:

$url = "http://www.google.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
Run Code Online (Sandbox Code Playgroud)

见:cURL


Ade*_*mar 5

尝试用这个函数代替 file_get_contents():

<?php

function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
Run Code Online (Sandbox Code Playgroud)

它可以像 file_get_contents() 一样使用,但使用 cURL。

在 Ubuntu(或其他具有 aptitude 的类 UNIX 操作系统)上安装 cURL:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart
Run Code Online (Sandbox Code Playgroud)

另请参见卷曲


Spu*_*ley 2

这几乎肯定是由允许 PHP 禁用使用文件处理函数打开 URL 的配置设置引起的。

如果您可以更改 PHP.ini,请尝试打开该allow_url_fopen设置。另请参阅fopen 的手册页了解更多信息(相同的限制影响所有文件处理函数)

如果您无法打开该标志,则需要使用其他方法(例如 Curl)来读取您的 URL。