<?php
/**
* Exports results from text files for maintenance tasks.
*
* @param string $directory The directory containing the text files.
* @param string $outputFile The path to the output CSV file.
* @return bool True on success, false on failure.
*/
function exportMaintenanceResults(string $directory, string $outputFile): bool
{
// Validate input
if (!is_dir($directory)) {
error_log("Error: Directory '$directory' does not exist.");
return false;
}
if (empty($outputFile)) {
error_log("Error: Output file path cannot be empty.");
return false;
}
// Open the output file for writing
$fp = fopen($outputFile, 'w');
if ($fp === false) {
error_log("Error: Could not open output file '$outputFile' for writing.");
return false;
}
// Get a list of all text files in the directory
$files = scandir($directory);
if ($files === false) {
error_log("Error: Could not read directory '$directory'.");
fclose($fp);
return false;
}
// Iterate over the files
foreach ($files as $file) {
// Skip "." and ".." directories
if ($file == '.' || $file == '..') {
continue;
}
// Check if the file is a text file (you can adjust the extension filter)
if (pathinfo($file, PATHINFO_EXTENSION) != 'txt') {
continue;
}
// Read the content of the text file
$content = file_get_contents($directory . '/' . $file);
if ($content === false) {
error_log("Error: Could not read file '$file'.");
continue;
}
// Process the content (example: split into lines)
$lines = explode("\n", $content);
// Write the data to the output file (CSV format)
foreach ($lines as $line) {
//Escape commas if needed.
$escapedLine = str_replace(',', ';', $line);
fputcsv($fp, [$escapedLine]); // write each line as a separate row
}
}
// Close the output file
fclose($fp);
return true;
}
// Example Usage:
$directory = './maintenance_reports'; // Replace with your directory
$outputFile = './maintenance_results.csv'; // Replace with your desired output file
if (exportMaintenanceResults($directory, $outputFile)) {
echo "Maintenance results exported to '$outputFile' successfully.\n";
} else {
echo "Error exporting maintenance results.\n";
}
?>
Add your comment