I was wondering how to save PHP variables to a txt file and then retrieve them again.
Example:
There is an input box, after submitted the stuff that was written in the input box will be saved to a text file. Later on the results need to be brought back as a variable. So lets say the variable is $text I need that to be saved to a text file and be able to retrieve it back again.
Syntax: $variable = "value"; $$variable = "new_value"; $variable is the initial variable with the value. $$variable is used to hold another value.
A variable in PHP is a name of memory location that holds data. In PHP, a variable is declared using $ sign followed by variable name. The main way to store information in the middle of a PHP program is by using a variable.
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.
This should do what you want, but without more context I can't tell for sure.
Writing $text
to a file:
$text = "Anything"; $var_str = var_export($text, true); $var = "<?php\n\n\$text = $var_str;\n\n?>"; file_put_contents('filename.php', $var);
Retrieving it again:
include 'filename.php'; echo $text;
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file'; $content = serialize($my_variable); file_put_contents($file, $content); $content = unserialize(file_get_contents($file));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With