使用PHP将数据从数据库提取到文本文件[Codeigniter]

时间:2019-05-22 04:05:58

标签: php codeigniter header

我有此代码

    $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);

从表数据中获取数据,并将其以这种格式插入到名为data.txt的文件中

USERNAME | qwq / DATA | www。

我的问题是代码仅记录一条数据,因为数据存储在单个字符串中,如何使它获取所有记录?

编辑#1 我找到了解决方案,这是新的工作代码

    $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);

1 个答案:

答案 0 :(得分:0)

尝试此代码:

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

希望这对您有帮助