问题描述
<?PHP
// $target = "http://www.example.com/";
$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
$output = "";
// Fetch the file.
if($file_handle = fopen($target,'r')) {
while (($buffer = fgets($file_handle,4096)) !== false) {
$output = $output . $buffer;
}
if(!feof($file_handle)) {
$output = "Error: Unexpected fgets fail\n";
}
fclose($file_handle);
} else {
die("Error: fopen Failed\n");
}
echo $output;
?>
我不断收到上述 URL 的错误:
Warning: fopen(http://www.schrenk.com/nostarch/webbots/hello_world.html/): Failed to open stream: HTTP request Failed! HTTP/1.1 400 Bad Request in <code.PHP> on line 3
但是,该代码适用于“http://www.example.com”、“https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview”等其他网址。
请帮我调试一下。
解决方法
正如所怀疑的那样,该站点不允许机器人从中读取数据。作为一种解决方法,您可以模拟浏览器用户代理,使站点相信请求来自实际浏览器。此外,使用 fopen()
阅读很乏味。如果您只想完全捕获响应,curl
是更好的选择。
片段:
<?php
try{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://www.schrenk.com/nostarch/webbots/hello_world.html');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/89.0.4389.114 Safari/537.36");
$response = curl_exec($ch);
if(curl_errno($ch) !== 0){
throw new \Exception(curl_error($ch));
}
curl_close($ch);
echo $response;
}catch(\Exception $e){
die("Error: " . $e->getMessage());
}