0

我在尝试使用 fsockopen 和 fgets 获取网页内容时遇到问题。我可以轻松地从 Web 服务器接收标头,如下所示:

HTTP/1.1 200 OK 
[cache-control] => private 
[content-type] => text/plain; charset=utf-8 
[server] => Microsoft-IIS/7.0
[x-aspnet-version] => 2.0.50727
[x-powered-by] => ASP.NET
[date] => Sat, 23 Jul 2011 10:36:57 GMT
[connection] => close
[content-length]=> 30072 
[vary] => Accept-Encoding [content-encoding] => gzip

我的代码如下:

$fp = @fsockopen(“www.abc.com”, 80, $errno, $errstr, 30);
fwrite($fp, $request);//$request is my predefined header including path and cookies
$lines=””;
while (!feof($fp)) 
{
  Echo “fgets start at ”.date(“H:i:s”).”\n”;
  $line = fgets($fp, 4096);
  Echo strlen($line) .”\n”;
  Echo “fgets end at ”.date(“H:i:s”) .”\n”;
  $lines +=$line;
}
fclose($fp);

输出是这样的:

……
fgets start at 12:23:45
219
Fgets end at 12:23:47
……

我真的很想知道为什么只需要 2 秒才能获得 219 字节的数据。它太慢了。要获取整个页面,包括数百个 fget 迭代,它需要 40 秒。而如果你使用Firefox,它只是一秒钟..

我想知道是什么导致 fgets 变得太慢。

感谢您的阅读。

4

1 回答 1

1

出乎我的意料:连接是否有可能因为您使用的是 HTTP/1.1 请求而保持打开状态?这将使服务器等待您发出另一个请求,如果没有找到关闭连接(视为超时)。除此之外,您的操作系统可能正在缓冲数据(SO_RCVLOWAT socket_option),因此当 Web 服务器关闭连接时读取结束。

尝试减少循环内要读取的数据量(如 128 字节),看看会发生什么。除此之外(与此相关),您可能想尝试阅读以下内容: http: //ar.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

php 可能无法很好地阅读 EOL

于 2011-07-23T16:59:44.263 回答