2

我知道 file_get_contents 可用于检索网页的来源,但我想知道最有效的方法。

我有一个很久以前制作的旧课程,它使用这样的东西:

    $this->socket = fsockopen($this->host, 80);

    fputs($this->socket, 'GET ' . $this->target . ' HTTP/1.0' . "\n");
    fputs($this->socket, 'Host: ' . $this->host . "\n"); 
    fputs($this->socket, 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5' . "\n");
    fputs($this->socket, 'Connection: close' . "\n\n");

    $this->source = '';

    while(!feof($this->socket))
    {
        $this->source .= fgets($this->socket, 128);
    }

    fclose($this->socket);

这是最好的方法吗?最有效的意思是返回最快的结果。

4

5 回答 5

4

file_get_contents()是最好和最有效的方法。但是,无论哪种方式,都没有太大区别,因为瓶颈是网络,而不是处理器。代码可读性也应该是一个问题。

也考虑这个基准:http ://www.ebrueggeman.com/php_benchmarking_fopen.php

于 2009-03-29T19:42:28.033 回答
3

您拥有的代码可能是执行您所说的最快和最简单的方法。但是,如果您想要执行更复杂的任务(例如发布或支持 HTTP 1.1 内容,例如 Content-Encoding 和 Transfer-Encoding),它就不是很灵活。

如果您想要一些可以处理更复杂情况等的东西,请使用 php cURL

于 2009-03-29T19:42:16.020 回答
1

没有把握?让我们测试一下!下面的脚本example.org使用这两种方法打开了 10 次:

$t = microtime(true);
$array = array();
for($i = 0; $i < 10; $i++) {
    $source = file_get_contents('http://www.example.org');
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10; $i++) {
    $socket = fsockopen('www.example.org', 80);
    fputs($socket, 'GET / HTTP/1.0' . "\n");
    fputs($socket, 'Host: www.example.org' . "\n"); 
    fputs($socket, 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5' . "\n");
    fputs($socket, 'Connection: close' . "\n\n");
    $source = '';
    while(!feof($socket)) {
        $source .= fgets($socket, 128);
    }
    fclose($socket);
}
print microtime(true) - $t;

第一次运行:

file_get_contents: 3.4470698833466
fsockopen: 6.3937518596649

第二次运行:

file_get_contents: 3.5667569637299
fsockopen: 6.4959270954132

第三次运行

file_get_contents: 3.4623680114746
fsockopen: 6.4249370098114

因此,由于file_get_contents更快更简洁,我将宣布它为获胜者!

于 2009-03-30T01:40:18.487 回答
0

还要检查 Zend Framework 的Zend_Http_Client类。它支持重定向等。

于 2009-03-29T19:56:57.593 回答
0

你不会得到比内置的 file_get_contents 像这样的自制代码更好的性能。实际上,短至 128 字节(?为什么?)的字符串的常量连接会表现得相当糟糕。

对于 HTTP,有理由自己动手或使用外部库,例如:

  • 您需要控制网络超时

  • 您想直接从套接字流式传输内容而不是累积它

但性能不是其中之一;简单的内置PHP功能将仅受网络速度的限制,这是您无能为力的。

于 2009-03-30T01:26:34.337 回答