PHP - 这是获取 html 内容最快最好的方法

PHP - which are fastest and best way to get html content

我必须阅读一个 URL html 大约 1 MB 的内容,正好是 926 KB。 我已经创建了 2 个函数。

文件大小为 ~1 MB 的 URL 内容:

https://example.com/html_1MB_Content.html

下面是我创建的 2 个函数:

function getContent1 ($url) {
    $file_handle = fopen($url, "r");
    while (!feof($file_handle)) {
       $line = fgets($file_handle);
            echo $line;
    }
    fclose($file_handle);
}

function getContent2 ($url) {
    $handle = curl_init($url);
    curl_setopt_array($handle, array(
        CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
        CURLOPT_ENCODING => '', 
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_FOLLOWLOCATION => 1
    ));
    $curl_response = curl_exec($handle);
    curl_close($handle);
    return $curl_response;
}

$testUrl = 'https://example.com/html_1MB_Content.html';

$result1 = getContent1 ($testUrl);

$result2 = getContent2 ($testUrl);

我想要的是最快更少内存。在这种情况下哪个最好?

还有一个问题,无论如何都是从下往上阅读页面内容,如果找到数据就停止阅读了?

如果你想知道执行你的代码需要多长时间,你可以使用这对代码..

//put this to the start of your code..
$time_start = microtime(true); 

//here goes your code...

//and put this to the end of your code...
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start).'. memory used in kb : '.echo memory_get_usage();

这将显示以秒为单位的性能时间和以 KB 为单位的已用内存大小...