SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Columnist Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,066
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Most efficient way of reading file contents into a variable?

    Just out of curiosity really, but does anyone know which is more efficient?
    Code:
    $contents = implode('', file('filename.txt'));
    or
    Code:
    $fp = fopen('filename.txt, 'r');
    $contents = fread($fp, filesize('filename.txt'));
    fclose($fp);
    or even
    Code:
    $fp = fopen('filename.txt, 'r');
    $buffer = '';
    while (!feof ($fp)) {
    	$buffer .= fgets($fp, 4096);
    fclose($fp);

  2. #2
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've always used $contents = implode('', file('filename.txt')); since it's a one liner, I have done some testing before, and the time had very little difference, but my file wasn't that big either....
    Work smarter, not harder. -Scrooge McDuck

  3. #3
    SitePoint Zealot
    Join Date
    Sep 2000
    Location
    Seattle, WA area
    Posts
    104
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did some quick benchmarks. I had each of your code segments load the PHP install.txt file (About 26KB) 100 times. Recorded the running time for each test 5 times, and averaged them. Here's what my results were:

    PHP Code:
    $contents implode(''file('install.txt')); 
    Avg. Time for 100 file loads: 0.417722 seconds

    PHP Code:
    $fp fopen('install.txt''r');
    $contents fread($fpfilesize('install.txt'));
    fclose($fp); 
    Avg. Time for 100 file loads: 0.07808 seconds

    There may have been an error in my tests (And yes, I did check that the file was actually getting read by having it echo to the browser), but the results appear fairly conclusive as to which was the fastest.

    Anyone care to comment on these results?
    Last edited by dcsonic2k; Mar 4, 2002 at 20:55.
    David Baxter
    Freelance PHP/MySQL Developer
    Contact me for more information: [ Email ] [ICQ: 47136518]


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •