Skip to content

Instantly share code, notes, and snippets.

@muathendirangu
Created March 3, 2024 20:26
Show Gist options
  • Save muathendirangu/c293dd8d391ca06e7f3f482bd0e25228 to your computer and use it in GitHub Desktop.
Save muathendirangu/c293dd8d391ca06e7f3f482bd0e25228 to your computer and use it in GitHub Desktop.
Here's a PHP script that reads a text file, counts the words in the file
<?php
// Define the filename
$filename = "file_name.txt";
try {
// Open the file for reading
$file = fopen($filename, "r");
// Check if the file was opened successfully
if ($file) {
// Initialize word count
$wordCount = 0;
// Read the file line by line
while (($line = fgets($file)) !== false) {
// Split the line into words using explode and trim each word
$words = array_map('trim', explode(" ", $line));
// Count the number of words in the current line
$wordCount += count($words);
}
// Close the file
fclose($file);
// Display the word count
echo "The file '{$filename}' contains {$wordCount} words.";
} else {
// Exception thrown if file opening fails
throw new Exception("Error: Could not open file '{$filename}'.");
}
} catch (Exception $e) {
// Display error message if an exception is thrown
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment