1.2.625. Joining file()¶
Use file() to read lines separately.
Applying join('', )
or implode('', )
to the result of file() provides the same results than using file_get_contents(), but at a higher cost of memory and processing.
If the delimiter is not ''
, then implode()
and file()
are a better solution than file_get_contents()
and str_replace()
or nl2br()
.
Always use file_get_contents()
to get the content of a file as a string. Consider using readfile() to echo the content directly to the output.
This analysis also checks for the reverse feature: loading a file with file_get_contents()
and splitting it into rows with explode()
or an alternative. Such association should be replaced by a single call to file()
, with may be the FILE_IGNORE_NEW_LINES
.
<?php
// memory intensive
$content = file_get_contents('path/to/file.txt');
// memory and CPU intensive
$content = join('', file('path/to/file.txt'));
// Consider reading the data line by line and processing it along the way,
// to save memory
$fp = fopen('path/to/file.txt', 'r');
while($line = fget($fp)) {
// process a line
}
fclose($fp);
// Reverse feature
$file = file_get_contents('/path/to/file.txt');
$rows = explode(PHP_EOL, $file);
?>
See also file_get_contents, file and explode.
1.2.625.1. Connex PHP features¶
1.2.625.1.1. Suggestions¶
Use file_get_contents() instead of implode(file()) to read the whole file at once.
Use readfile() to echo the content to standard output
stdout
at once.Use fopen() to read the lines one by one, generator style.
1.2.625.1.2. Specs¶
Short name |
Performances/JoinFile |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Examples |
|
Available in |