PHP file() Function
Definition
The file() reads a file into an array.
Each array element contains a line from the file with newline attached.
Syntax
file(path,include_path,context)
Parameter
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.
Return
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.
Example 1
Convert file to an array with each line an element inside that array, use the file() function:
<?PHP/*from w w w. j av a 2s . co m*/
$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";
}
?>
Example 2
Output a file as an array
<?php
print_r(file("test.txt"));
?>
The code above generates the following result.