How to create and save as .txt from a text input in php


 

In PHP, you can create a simple script to take text input from a user and save it as a .txt file. Here's a basic example:

php
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // Get the text input from the form $text = $_POST["text_input"]; // Specify the file name and path $file_name = "output.txt"; // Open the file in write mode and save the text if (file_put_contents($file_name, $text) !== false) { echo "Text saved to $file_name"; } else { echo "Error saving the text to $file_name"; } } ?> <!DOCTYPE html> <html> <head> <title>Save Text to .txt File</title> </head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="text_input">Enter text:</label><br> <textarea name="text_input" id="text_input" rows="4" cols="50"></textarea><br> <input type="submit" value="Save Text"> </form> </body> </html>

Save the above code in a PHP file, for example, save_to_text_file.php, and place it in a web server directory. When you open this file in a web browser, you'll see a form where you can enter text. After submitting the form, the entered text will be saved to a file named output.txt in the same directory as the PHP script.

You can customize the file name and path as needed, and you can expand this example to handle more complex scenarios, such as appending to an existing file, saving the file to a specific location, or implementing better error handling.

Viewers
Read Also

No comments:

Post a Comment

SEARCH