繁体   English   中英

通过PHP检索网站源的最有效方法? (GET请求)

[英]Most efficient way to retrieve the source of a website through PHP? (GET Request)

我知道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);

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

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

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

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

如果你想要处理更复杂案例等的东西,请使用php cURL

不确定? 我们来试试吧! 下面的脚本使用两种方法打开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

第3次运行

file_get_contents: 3.4623680114746
fsockopen: 6.4249370098114

因此,由于file_get_contents更快更简洁,我将宣布它是赢家!

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

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

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

  • 你需要控制网络超时

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

但表现不是其中之一; 简单的内置PHP函数将仅受网络速度的限制,这是您无法做任何事情的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM