[英]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.