This should demonstrate how to read a simple text file in a PHP using 3 different methods, the first being the most efficient in terms of memory usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php /* * Reading the contents of a file using fopen/fgets/fclose */ $fp = fopen("/tmp/inputfile.txt", "r"); if ($fp) { // fgets reads until it hits a newline, or the buffer size. while (($buffer = fgets($fp, 1024)) !== false) { $lines[] = $buffer; } // only close if you successfully opened the file. fclose($fp); } else { die("error opening file"); } /* * Reading the contents of a file using file() */ if( ($lines = file("/tmp/inputfile.txt")) !== FALSE ) { // do something with the lines } else { die("error opening file"); } /* * Reading the contents of a file using file_get_contents() and using explode to get the lines */ if( ($file_contents = file_get_contents("/tmp/inputfile.txt")) !== FALSE ) { $lines = explode("\n", $file_contents); // do something with the lines } else { die("error opening file"); } ?> |