The file() reads a file into an array.
Each array element contains a line from the file with newline attached.
file(path,include_path,context)
Parameter | Is Required | Description |
---|---|---|
path | Required. | File to read |
include_path | Optional. | Set to '1' to search for the file in the include_path (in php.ini) as well |
context | Optional. | Context of the file handle. Skip using NULL. |
Context a set of options can modify the behavior of a stream.
Returns the file in an array.
Each element of the array corresponds to a line in the file with the newline attached. If failure, file() returns FALSE.
Convert file to an array with each line an element inside that array, use the file() function:
<?PHP//from w w w .j a v a 2 s.c om
$filename = "c:/abc/test.txt";
$filearray = file($filename);
if ($filearray) {
while (list($var, $val) = each($filearray)) {
++$var;
$val = trim($val);
print "Line $var: $val<br />";
}
} else {
print "Could not open $filename.\n";
}
?>
Output a file as an array
<?php
print_r(file("test.txt"));
?>
The code above generates the following result.
The following code shows how to use the optional flags parameter since PHP 5 for file function.
<?php
$trimmed = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo $trimmed;
?>
The code above generates the following result.