The need for this information began with the requirement that we would be provided a CSV spreadsheet with information that would need to be extracted, modified, and recompiled into a new CSV which could then be imported to a website. As an extra feature, I decided that I would like to have some kind of logging take place and a message upon completion. The file we are reading would always have the same name and a function that reads that file, does things, logs things, and spits out an export file. To go into those details is beyond the scope of this post but the provided examples will get you going. I kept it simple for now, since the task is not that complex.
/**
* Create a log file in the same directory
*/
function create_log_file() {
$todays_date_and_time = date("YmdHi");
$file_name = $todays_date_and_time . '_log.txt';
$fp = fopen( $file_name, 'w' );
fclose( $fp );
return $file_name;
}
/**
* Create the export file in the same directory
*/
function create_export_file() {
$todays_date_and_time = date("YmdHi");
$file_name = $todays_date_and_time . '_export.csv';
$fp = fopen( $file_name, 'w' );
fclose( $fp );
return $file_name;
}
/**
* Write to the specified log file
* $log_file_name is the name of the file to be written to and is generated with the create_log_file function
* $message will be added to the log file along with a timestamp
*/
function write_to_log( $log_file_name, $message ) {
$timestamp = date("Ymd h:i:s A");
$log_file = fopen($log_file_name, "a");
fwrite($log_file, "\n{$timestamp}: {$message}");
fclose( $log_file );
}
Since this runs when the page/script is accessed, it might be nice to give some kind of visual cue that something happened. I chose to do this by echoing the following HTML on the page once the operation completed successfully.
echo "<h1>Operation Complete 👍</h1><p>The file, {$file_name}, was processed successfully. The exported file is <a href='/{$export_file_name}'>{$export_file_name}</a>.</p>";
Additional features to consider would include data validation, error checking and handling, or even an interface that allows the user to upload a file to start the process. Below are some of the resources I used to get through this task.