How to write php result to a .txt file ?

Discussion in 'PHP' started by Funk-woo10, Oct 24, 2008.

  1. #1
    Hi,

    I want to list the results from my database into .txt file, how can i do this in php ? is there any good tutorials ?

    Order,

    Check if text file exists (if not die !)
    If true, overwrite all contents with new results from database.

    Note: reults being pulled from the database will be in thousands..problem ?
     
    Funk-woo10, Oct 24, 2008 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    no problems at all.

    First you need to read from your query all information and create a buffer with all data that has to be writen to a file (variabel) and then use fopen, fputs and fclose to open the file, add content and close it!.

    That's all.
     
    EricBruggema, Oct 24, 2008 IP
    Funk-woo10 likes this.
  3. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #3
    You'll likely want to skip PHP for this task.
    There's a good chance your database server has a command available for exporting directly to a file.
     
    joebert, Oct 24, 2008 IP
  4. Equaite

    Equaite Active Member

    Messages:
    128
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    Digital Goods:
    1
    #4
    Here's a snippet that you can use after you've gotten the data from the database written into a variable:

    <?php
    	#open the file for writing only, erase contents
    	$fp = fopen('results.txt', 'w');
    	#write the contents of $results to the file
    	fwrite($fp, $results);
    	#close the file
    	fclose($fp);
    ?>
    PHP:
    I'll assume that the database records are in a variable called $results, but you can change this to whatever you like. This will write the contents of $results to a file called results.txt. Make sure that the file is writable, or that the directory is writable so that it can create the file if it does not exist. :)
     
    Equaite, Oct 24, 2008 IP
    Funk-woo10 likes this.
  5. Kyosys

    Kyosys Peon

    Messages:
    226
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #5
    or, if you don't want to use fopen
    you could do
    if(file_exists("file.txt")) file_put_contents("whatever");
    else die;
     
    Kyosys, Oct 24, 2008 IP