【发布时间】:2011-06-03 14:18:04
【问题描述】:
我尝试使用 file_get_contents 和 cURL 来获取网站的内容,我也尝试使用 Lynx 打开同一个网站,但无法获取内容。我收到了 406 Not Acceptable,似乎该网站会检查我是否使用浏览器。有解决办法吗?
【问题讨论】:
标签: php curl file-get-contents
我尝试使用 file_get_contents 和 cURL 来获取网站的内容,我也尝试使用 Lynx 打开同一个网站,但无法获取内容。我收到了 406 Not Acceptable,似乎该网站会检查我是否使用浏览器。有解决办法吗?
【问题讨论】:
标签: php curl file-get-contents
它可能期望用户代理是一个网络浏览器。您可以使用 cURL 轻松设置:
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
其中$useragent 是您要用于用户代理的字符串。尝试使用主要浏览器的一些常见浏览器,看看是否有帮助。此页面列出了一些common user agents。
【讨论】:
//make a call the the webpage to get his handicap
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.golfspain.com/portalgolf/HCP/handicap_resul.aspx?sLic=CB00693474");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt($ch, CURLOPT_REFERER, "http://google.com" );
curl_setopt($ch, CURLOPT_HEADER, TRUE );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
$header = array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Accept-Language: en-us;q=0.8,en;q=0.6'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$html = curl_exec($ch);
curl_close($ch);
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
【讨论】:
也许您必须设置更多 HTTP 标头,例如“真正的”浏览器。使用卷曲:
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
$header = array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Accept-Language: en-us;q=0.8,en;q=0.6'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
【讨论】: