To create and download a text file in PHP, you can follow these steps:
- Create the content of the text file as a string.
- Use the
file_put_contents()
function to write the content to a file on the server. - Set the appropriate HTTP headers to force a file download.
- Output the file contents to the browser.
Here’s an example PHP code that creates and downloads a text file:
<?php
// Create the content of the text file
$content = "This is some sample text.";
// Write the content to a file on the server
$file = 'example.txt';
file_put_contents($file, $content);
// Set the appropriate HTTP headers to force a file download
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
// Output the file contents to the browser
readfile($file);
?>
In this example, the file_put_contents()
function is used to write the content of the text file to a file named “example.txt” on the server. The header()
function is then used to set the appropriate HTTP headers to force a file download. Finally, the readfile()
function is used to output the contents of the file to the browser.
Note: The file download functionality will only work if this code is executed on a web server that supports PHP and has the necessary configuration to handle the header()
and readfile()
functions correctly.