我尝试从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()
。我能做些什么来让我的代码工作?
OK,远程文件可以访问。当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');