What are the advantages of using fgets() over file() for reading a file line by line in PHP?
When reading a file line by line in PHP, using fgets() is more memory-efficient than file(). This is because fgets() reads the file line by line, while file() reads the entire file into an array. If the file is large, using file() can consume a significant amount of memory. Therefore, fgets() is a better choice for reading large files in PHP.
$file = fopen('example.txt', 'r');
while ($line = fgets($file)) {
// Process each line here
echo $line;
}
fclose($file);
Keywords
Related Questions
- How can one access object properties in an array of objects in PHP for sorting purposes?
- How can tables be marked in HTML so they can be counted or selected for editing?
- Why is it recommended to use a dedicated mailer class instead of the mail() function in PHP for sending emails, and how can this improve email deliverability?