file_get_contents 使用 http - 无法打开流

file_get_contents with http - Failed to open stream

我尝试从 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设置为"On"。我也已经试过了 urlencode()。 我该怎么做才能让我的代码正常工作?

好的,远程文件可以访问。当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');