What is the best practice for counting the contents of multiple text files in a folder using PHP?
When counting the contents of multiple text files in a folder using PHP, the best practice is to loop through each file, read its contents, and increment a counter for each file. This can be achieved by using functions like scandir() to get a list of files in a directory and file_get_contents() to read the contents of each file.
$folder = 'path/to/folder';
$files = scandir($folder);
$totalCount = 0;
foreach($files as $file) {
if(is_file($folder . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) == 'txt') {
$content = file_get_contents($folder . '/' . $file);
$count = str_word_count($content);
$totalCount += $count;
}
}
echo "Total word count of all text files in the folder: " . $totalCount;
Keywords
Related Questions
- What potential pitfalls should be considered when deleting a file in PHP after an import process?
- How can the code in the forum thread be modified to achieve the desired output in the information.txt file?
- What are the best practices for ensuring that PHP scripts for database updates do not exceed the max_execution_time limit?