【问题标题】:PHP file_get_contents returning falsePHP file_get_contents 返回 false
【发布时间】:2013-01-25 22:52:58
【问题描述】:

也许我已经坐在这里太久了,但为什么file_get_contents 会在这里返回false?我已经剪切并粘贴了 URL,它可以正常工作吗?

$url = "http://jobs.github.com/positions.json?search=" . $as_any . "&location=" .       $location;
// URL contains http://jobs.github.com/positions.json?search=Project Manager&location=London
var_dump($url);
$json = file_get_contents($url);
var_dump($json);
$results = json_decode($json, TRUE);
var_dump($results);
exit;

编辑:

我已经检查了allow_url_fopen,它肯定是打开的。

【问题讨论】:

标签: php json


【解决方案1】:

您可能需要在 php.ini 中启用 allow_url_fopen

http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

来自文档:

此选项启用支持访问的 URL 感知 fopen 包装器 URL 对象,如文件。

您的服务器可能会阻止您使用 file_get_contents 打开位于 URL 中的文件。

【讨论】:

  • 目前 /etc/php.ini 有 allow_url_fopen = On
  • 如果 file_get_contents() 返回 false 那么它无法读取文件。如果值为 NULL,则函数本身被禁用。
  • 似乎不正确@NikhilMk,我得到了错误但启用后我得到了数据
【解决方案2】:

可能在你的 php.ini 中允许 url_fopen:http://php.net/manual/en/filesystem.configuration.php

需要被允许。

【讨论】:

    【解决方案3】:

    试试这个:

    $query = http_build_query(array('search'=>$as_any, 'location'=>$location));
    $url = "http://jobs.github.com/positions.json?" . $query;
    

    问题在于您没有对包含空格的搜索词进行 URL 编码。该请求从服务器返回 400 错误,如果您启用了错误报告,您会注意到这一点。

    【讨论】:

    • 简而言之,我爱你..我确实尝试过 $url = urlencode(....) 但这似乎不起作用,有什么区别?
    • 这将对 URL 中的所有分隔符进行编码,因此它们不会被识别为分隔符。
    【解决方案4】:

    有时如果 file_get_contents 返回 false(未找到),您应该查看 url 是否为 encoded

    例子:

    http://test.net/демо/

    应该是:

    https://test.net/%D0%B4%D0%B5%D0%BC%D0%BE/

    【讨论】:

      【解决方案5】:

      在我的例子中,用这个简单的函数替换 file_get_contents()

      function get_content($URL){
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_URL, $URL);
          $data = curl_exec($ch);
          curl_close($ch);
          return $data;
      }
      

      【讨论】:

      • 兄弟你救了我的命
      • 谢谢你救了我:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2016-10-24
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多