php - 如何在没有 CURL 的情况下获取网页内容?

标签 php curl stream

我需要获取网页内容,我无法使用 Curl,因为它未启用。我尝试了以下代码,但它不起作用。

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);   

$fp = fopen($_GET['url'], 'r', false, $context);
if($fp)
fpassthru($fp);
fclose($fp);
exit;

代码产生错误

Warning: fopen(http://www.google.com/search?&q=site:www.myspace.com+-intitle:MySpaceTV+%22Todd Terje%22) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 

最佳答案

您可以使用老式代码,例如:

$CRLF = "\r\n";
$hostname = "www.something.com";

$headers[] = "GET ".$_GET['url']." HTTP/1.1";
$headers[] = "Host: ".$hostname;
$headers[] = "Accept-language: en";
$headers[] = "Cookie: foo=bar";
$headers[] = "";

$remote = fsockopen($hostname, 80, $errno, $errstr, 5);
// a pinch of error handling here

fwrite($remote, implode($CRLF, $headers).$CRLF);

$response = '';

while ( ! feof($remote))
{
    // Get 1K from buffer
    $response .= fread($remote, 1024);
}

fclose($remote);

更新:这个解决方案的好处是它不依赖于 fopen 包装器。

关于php - 如何在没有 CURL 的情况下获取网页内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945887/

相关文章:

php - JSON 数据格式不正确 : fetching from mysql

php - 如何检查用户之前回复的帖子是否收到新回复?

php - fsockopen 在端口 25 和 587 上被阻止

java - Java 中的 JSON header 数组

windows-phone-7 - 在 windows phone 7 浏览器中流式传输音频

stream - 如何获取 twitch.tv 的流 key

scala - 如何将 for 循环 Seq 输出重写为 Stream 输出?

PHP Solr 安装不工作

php - 404在curl中找不到

python - 以 Curl 格式导出 Scrapy 请求