Save PHP variables to a text file

后端 未结 7 1568
梦如初夏
梦如初夏 2020-11-29 00:59

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 writ

相关标签:
7条回答
  • 2020-11-29 01:33

    for_example, you have anyFile.php, and there is written $any_variable='hi Frank';

    to change that variable to hi Jack, use like the following code:

    <?php
    $content = file_get_contents('anyFile.php'); 
    
    $new_content = preg_replace('/\$any_variable=\"(.*?)\";/', '$any_variable="hi Jack";', $content);
    
    file_put_contents('anyFile.php', $new_content);
    ?>
    
    0 讨论(0)
  • 2020-11-29 01:36

    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));
    
    0 讨论(0)
  • 2020-11-29 01:37

    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

    0 讨论(0)
  • 2020-11-29 01:38

    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;
    
    0 讨论(0)
  • 2020-11-29 01:38

    Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).

    It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.

    Usage:

    <?php
    require 'varDx.php';
    $dx = new \varDx\cDX; //create an object
    $dx->def('file.dat'); //define data file
    $val1 = "this is a string";
    $dx->write('data1', $val1); //writes key to file
    echo $dx->read('data1'); //returns key value from file
    

    See the github page for more information. It has functions to read, write, check, modify and delete data.

    0 讨论(0)
  • 2020-11-29 01:43

    Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)

    0 讨论(0)
提交回复
热议问题