PHP – Reading files

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.

<?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");
}

?>