Методы создания и загрузки текстовых файлов в PHP

Чтобы создать и загрузить текстовый файл на PHP, вы можете использовать несколько методов. Вот несколько вариантов:

Метод 1: использование file_put_contents() и header()

<?php
$fileContent = "This is the content of the text file.";
$fileName = "example.txt";
// Save the content to the file
file_put_contents($fileName, $fileContent);
// Set the appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
readfile($fileName);
exit;
?>

Метод 2: использование fopen(), fwrite() и fclose()

<?php
$fileContent = "This is the content of the text file.";
$fileName = "example.txt";
// Open the file for writing
$file = fopen($fileName, "w");
// Write the content to the file
fwrite($file, $fileContent);
// Close the file
fclose($file);
// Set the appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
readfile($fileName);
exit;
?>

Метод 3. Использование класса SplFileObject

<?php
$fileContent = "This is the content of the text file.";
$fileName = "example.txt";
// Create a new SplFileObject instance
$file = new SplFileObject($fileName, "w");
// Write the content to the file
$file->fwrite($fileContent);
// Set the appropriate headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
readfile($fileName);
exit;
?>

Эти методы позволяют создать текстовый файл с указанным содержимым, а затем заставить браузер загрузить его. Не забудьте заменить «example.txt» и «Это содержимое текстового файла». с желаемым именем файла и содержимым соответственно.