问题
I written simple php code to get some url content but it dosn't work it return this error
file_get_contents(http://www.nature.com/nature/journal/v508/n7496/full/nature13001.html) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
here is my code. please help me.tnx
$content=file_get_contents('http://www.nature.com/nature/journal/v508/n7496/full/nature13001.html');
echo $content;
回答1:
Here's an alternative to file_get_contents using cURL:
$url = 'http://www.example.com';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$data = curl_exec($curl);
curl_close($curl);
You might want to add this curl_setopt($curl, CURLOPT_ENCODING ,"");
if you encounter encoding problem.
回答2:
Open the page using your browser and with the console open, see that the server does indeed send a 401 even when page is sent and viewable
On php, open the url in an alternate way to ignore the error (see http://php.net/manual/en/context.http.php)
You'll also notice that it's gzip-encoded, see http://php.net/manual/en/function.gzinflate.php
Happy hacking!
来源:https://stackoverflow.com/questions/26028443/file-get-contents-http-request-failed