简体   繁体   中英

Extract data from database to text file with PHP [Codeigniter]

I have this code

    $dateFile = "data.txt";
    $data = $this->Setting->Loop("data");

    foreach($data->result() as $dat){
        $dataString = "USERNAME| ".$dat->user." / DATA| ".$dat->values_text.".\n";
        file_put_contents($dateFile,$dataString);
    }

    header('Content-Type: application/text');
    header('Content-Disposition: attachment; filename="'.$dateFile);
    echo file_get_contents($dateFile);

which get data from table data and insert it into file called data.txt with this format

USERNAME| qwq / DATA| www.

My problem is that the code take just one record of data because the data stored in a single string, how can I make it get all records?

Edit #1 I found a solution and this is the new working code

    $dateFile = "data.txt";
    $data = $this->Setting->Loop("data");
    $dataContent = array();
    $i =  0;

    foreach($data->result() as $dat){
        $i++;
        $dataContent[$i] = "USERNAME| ".$dat->user." / DATA| ".$dat->values_text.".\n";
    }

    file_put_contents($dateFile,$dataContent);
    header('Content-Type: application/text');
    header('Content-Disposition: attachment; filename="'.$dateFile);
    echo file_get_contents($dateFile);

Try this code:

$filename = __dir__.'test.php';
$data = 'This is sample text';
fopen($filename, 'w') or die('Cannot open file:  '.$filename);
fwrite($handle, $data);

Hope this will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM