How can the DateTime class in PHP be used to generate and format timestamps for filenames?

To generate and format timestamps for filenames using the DateTime class in PHP, you can create a new DateTime object with the current time, then format it as needed using the format() method. This allows you to customize the timestamp format for your filenames.

// Create a new DateTime object with the current time
$timestamp = new DateTime();

// Format the timestamp as needed (e.g. Y-m-d_H-i-s)
$filename = $timestamp->format('Y-m-d_H-i-s');

// Use the formatted timestamp in your filename
echo "Filename: " . $filename . ".txt";