當使用php5自帶的file_get_contents方法來獲取遠程文件的時候,有時候會出現file_get_contents(): failed to open stream: HTTP request failed!這個警告信息。
google或者baidu一下,好多這樣的問題,解決的方法都是修改PHP.ini,把allow_url_fopen給啓用,改成 allow_url_fopen = On
這樣做可以解決某些人的問題,有人說在php.ini中,有這樣兩個選項:allow_url_fopen =on(表示可以通過url打開遠程文件),user_agent="PHP"(表示通過哪種腳本訪問網絡,默認前面有個 " ; " 去掉即可。)重啓服務器。
但是有些還是會有這個警告信息,想用完美的解決還差一步,還得設置php.ini裏面的user_agent,php默認的user_agent是PHP,我們把它改成Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)來模擬瀏覽器就可以了
user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
在工作中遇到這個問題,後完美解決,故分享給大家。
<?php ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)"); $data_content = file_get_contents( $url );
但是最好的方式還是使用 curl 來抓取就行了,看來還是curl比較強悍
原文地址:完美解決failed to open stream: HTTP request failed!(file_get_contents引起的)
標籤:php file_get_contents failed