1. <?php
  2. /**
  3. * Exports results from text files for maintenance tasks.
  4. *
  5. * @param string $directory The directory containing the text files.
  6. * @param string $outputFile The path to the output CSV file.
  7. * @return bool True on success, false on failure.
  8. */
  9. function exportMaintenanceResults(string $directory, string $outputFile): bool
  10. {
  11. // Validate input
  12. if (!is_dir($directory)) {
  13. error_log("Error: Directory '$directory' does not exist.");
  14. return false;
  15. }
  16. if (empty($outputFile)) {
  17. error_log("Error: Output file path cannot be empty.");
  18. return false;
  19. }
  20. // Open the output file for writing
  21. $fp = fopen($outputFile, 'w');
  22. if ($fp === false) {
  23. error_log("Error: Could not open output file '$outputFile' for writing.");
  24. return false;
  25. }
  26. // Get a list of all text files in the directory
  27. $files = scandir($directory);
  28. if ($files === false) {
  29. error_log("Error: Could not read directory '$directory'.");
  30. fclose($fp);
  31. return false;
  32. }
  33. // Iterate over the files
  34. foreach ($files as $file) {
  35. // Skip "." and ".." directories
  36. if ($file == '.' || $file == '..') {
  37. continue;
  38. }
  39. // Check if the file is a text file (you can adjust the extension filter)
  40. if (pathinfo($file, PATHINFO_EXTENSION) != 'txt') {
  41. continue;
  42. }
  43. // Read the content of the text file
  44. $content = file_get_contents($directory . '/' . $file);
  45. if ($content === false) {
  46. error_log("Error: Could not read file '$file'.");
  47. continue;
  48. }
  49. // Process the content (example: split into lines)
  50. $lines = explode("\n", $content);
  51. // Write the data to the output file (CSV format)
  52. foreach ($lines as $line) {
  53. //Escape commas if needed.
  54. $escapedLine = str_replace(',', ';', $line);
  55. fputcsv($fp, [$escapedLine]); // write each line as a separate row
  56. }
  57. }
  58. // Close the output file
  59. fclose($fp);
  60. return true;
  61. }
  62. // Example Usage:
  63. $directory = './maintenance_reports'; // Replace with your directory
  64. $outputFile = './maintenance_results.csv'; // Replace with your desired output file
  65. if (exportMaintenanceResults($directory, $outputFile)) {
  66. echo "Maintenance results exported to '$outputFile' successfully.\n";
  67. } else {
  68. echo "Error exporting maintenance results.\n";
  69. }
  70. ?>

Add your comment