How can PHP be used to automatically categorize data based on specific keywords in a file?

To automatically categorize data based on specific keywords in a file using PHP, you can read the file line by line, search for the keywords, and then assign the data to appropriate categories based on the presence of these keywords. You can use PHP's file handling functions and string manipulation functions to achieve this.

<?php
// Open the file for reading
$filename = 'data.txt';
$file = fopen($filename, 'r');

// Define categories and keywords
$categories = ['Category A', 'Category B', 'Category C'];
$keywords = ['keyword1', 'keyword2', 'keyword3'];

// Read the file line by line
while (($line = fgets($file)) !== false) {
    // Check for keywords in each line
    foreach ($keywords as $keyword) {
        if (stripos($line, $keyword) !== false) {
            // Assign data to appropriate category
            if (stripos($line, $keywords[0]) !== false) {
                $category = $categories[0];
            } elseif (stripos($line, $keywords[1]) !== false) {
                $category = $categories[1];
            } elseif (stripos($line, $keywords[2]) !== false) {
                $category = $categories[2];
            }
            
            // Process the data based on category
            echo "Data: $line - Category: $category\n";
        }
    }
}

// Close the file
fclose($file);
?>