tags:

views:

93

answers:

3

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.

Hope it makes sense,

Thanks in advance!!!

+1  A: 

Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.

http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php

Kerry
Thank you for your caring.Unfortunately, I think you don't get me.
Ajith
@Ajith what's wrong with this answer?
Col. Shrapnel
I'd like to know as well?
Kerry
There is no problem with the references.Which is very helpful.Thank you once again.But, this is not actually what I am looking for.
Ajith
You asked for a way to write contents to a find (fwrite) and a way to read it back into a variable (fread) I personally agree that Christian's answer is better, but this does the same thing.
Kerry
Ajith, if my answer solved your question, then this one would have also as 'file_put_contents' is simply a wrapper function for the functions in Kerry's answer. Perhaps we both misunderstood though?
Christian
You have to put more effort in describing what you want then if none of the suggestions here help.
Helen Neely
+10  A: 

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));
Christian
alternate approach: http://stackoverflow.com/questions/2237291/php-reading-file/2237315#2237315
Gordon
A: 

This should do what you want, but without more context I can't tell for sure.

Writing $text to a file:

$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;
Sandeep Shetty
@Sandeep thank you very much.You are a genius.Actually this is what I am looking for...!!Working perfectly.Thanks again dear friend
Ajith