Search code examples
phphtmlfopenfgets

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


I have to read an URL html content about ~1 MB, exactly is 926 KB. And I already create 2 functions.

An URL content with filesize ~1 MB:

https://example.com/html_1MB_Content.html

And here are 2 functions that I was created:

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);

What I want is fastest and less memory. Which is best in this case?

One more question is anyway to read page content from bottom to top, if found data stop reading?


Solution

  • if you want to know how long it takes to execute your code, you may use these couple of code..

    //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();
    

    this will show you performance time in second and size of used memory in KB...