PHP write to file

前端 未结 6 1862
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 14:49

below is some code I am using to \"translate\" a map array into SQL code so I can easily update my database when I have updated my game map. As you can see it prints out the

相关标签:
6条回答
  • 2021-01-15 15:06

    There is an even simpler approach:

    ob_start();
    # Your code here ...
    file_put_contents('yourfile.txt', ob_get_clean());
    
    0 讨论(0)
  • 2021-01-15 15:11

    +my 2 cents:

    You may check your database servers mass data loading features, as most of them can load files in batch faster than performing thousands of inserts.

    0 讨论(0)
  • 2021-01-15 15:19

    That should be quite simple. Add

    // second parameter 'a' stands for APPEND
    $f = fopen('/path/to/the/file/you/want/to/write/to', 'a');
    

    to the beginning of your script.

    Add

    fclose($f);
    

    to the end fo your script to cleanly close the file handle (good pratice even though handles would be closed the the terminating script automatically).

    And the change all your echo's and prints to

    fwrite($f, '<<your string>>');
    

    EDIT:

    That way you can even compress the data on the fly using a compression stream wrapper if amnount of data gets really large.

    0 讨论(0)
  • 2021-01-15 15:25

    write all the lines and then send the file to the client.

    Check this post for further instructions

    0 讨论(0)
  • 2021-01-15 15:27

    If this is something you plan on writing on a regular interval or by different scripts, look at using flock() to lock the file and prevent data corruption.

        $fp = fopen("/tmp/lock.txt", "w+");
    
    if (flock($fp, LOCK_EX)) { // do an exclusive lock
        fwrite($fp, "Write something here\n");
        flock($fp, LOCK_UN); // release the lock
    } else {
        echo "Couldn't lock the file !";
    }
    
    fclose($fp);
    
    0 讨论(0)
  • 2021-01-15 15:28
    $str = <<<your string comes here>>>
    if( $fh = @fopen( "myfile.txt", "a+" ) ) {
                fputs( $fh, $str, strlen($str) );
                fclose( $fh );
    }
    

    this should do...

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