【问题标题】:file_get_contents with http - Failed to open stream带有 http 的 file_get_contents - 无法打开流
【发布时间】:2016-01-16 21:45:00
【问题描述】:

我尝试使用 PHP 中的file_get_contents()-函数从网站获取文本。

        $myVariable = file_get_contents('myUrl/json/file.json?jsonp=loadSomething);

不幸的是,我一直收到消息

"Warning:
file_get_contents(myUrl/json/file.json?jsonp=loadSomething): 
failed to open stream: HTTP request failed! 
HTTP/1.1 404 Not Found in *path of my .php- file* on line 10"

在 php.ini 中,allow_url_fopen 设置为“开启”。我也已经尝试过urlencode()。 我该怎么做才能让我的代码正常工作?

【问题讨论】:

  • 而您(即 www 用户)对该目录具有读取权限?
  • 你是什么意思?代码位于模块的“helper.php”文件中,安装在我的 Joomla 页面上,所以我相信 www 用户具有读取权限。
  • 我的意思是,您对json/ 有适当的用户权限吗?但是,如果您还没有这样做,请尝试使用绝对路径。
  • 我尝试打开的文件在另一个网站上。我可以毫无问题地在浏览器中打开 URL,它会向我显示纯文本消息。这就是消息,我想保存在我的变量中。因此,作为 www 用户,我确实可以访问“file.json”。

标签: php http web fopen


【解决方案1】:

好的,远程文件可以访问了。当file_get_contents 失败时,cURL 是你的朋友:

function file_get_contents_curl($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

现在试试

$myVariable = file_get_contents_curl('myUrl/json/file.json?jsonp=loadSomething');

【讨论】:

  • 感谢您的回复。我现在没有收到任何警告或错误,但我仍然没有正确收到网站的文本。调用该函数似乎只返回“0”。
  • @msu-welle - 我开始相信您的远程站点会积极尝试防止抓取等...查看更新,试图伪造您的呼叫是由浏览器通过CURLOPT_USERAGENT 发出的。跨度>
猜你喜欢
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 2020-10-02
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多