How can PHP be used to determine if a specific word is present in a CSV file and how many times it appears?
To determine if a specific word is present in a CSV file and count how many times it appears, you can read the CSV file line by line, explode each line by the delimiter (usually a comma), and then iterate through the exploded values to check for the specific word. You can keep a count of how many times the word appears as you iterate through the file.
<?php
$wordToFind = 'specific_word';
$csvFile = 'example.csv';
$wordCount = 0;
if (($handle = fopen($csvFile, 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
foreach ($data as $value) {
if (strpos($value, $wordToFind) !== false) {
$wordCount++;
}
}
}
fclose($handle);
}
echo "The word '{$wordToFind}' appears {$wordCount} times in the CSV file.";
?>
Keywords
Related Questions
- In what ways can PHP frameworks or libraries simplify the process of creating a secure user registration and login system with MySQL integration?
- What error was encountered in the PHP script and how was it resolved?
- What are common challenges when searching for a key in a multidimensional array using a text string in PHP?