0

I am trying to create a TXT file with PHP. This works fine. Unfortunately, it seems that I do not have the correct syntax, because there is no content inserted using the file_put_contents function to put the data from my SQLite table into the TXT file.

<?php
$db = new SQLite3('sshTunnel.sqlite');
$results = $db->query('SELECT * FROM mydata');

$file = 'D:\test.txt';
file_put_contents($file, $results);
?>

The file is written, but it contains 0 Bytes.

sjantke
  • 605
  • 4
  • 9
  • 35

2 Answers2

2

If there are rows, $results will contain an SQLite3Result object. You still need to loop over the result set to get the data.

For example:

while ($row = $results->fetchArray()) {
    file_put_contents($file, implode(', ', $row), FILE_APPEND);
}

Note that this is just an example, there are dedicated functions to write CSV if you need that.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Great, it seems to work. The results are unformatted. Is there a short way to write the content structured? – sjantke Jun 24 '16 at 14:31
  • Again, if you dump the `$row` object you can see how it is structured internally, and format any fields it may contain to your choice of structure. – Juan Tomas Jun 24 '16 at 14:33
  • How about tabs? And at the moment, I even get those, which have been deleted by now. How can that be? – sjantke Jun 24 '16 at 14:49
  • @gpuk360 if they're in the results, they're not deleted. They may be soft deleted though. – apokryfos Jun 24 '16 at 14:53
  • @apokryfos You are right. This problem is solved. Thanks! – sjantke Jun 24 '16 at 15:02
0

try output buffering:

ob_start() ;
var_dump($results) ;
file_put_contents($file, ob_get_clean()) ;
Juan Tomas
  • 4,905
  • 3
  • 14
  • 19
  • `$results` will contain a boolean or a SQLite3Result object. – jeroen Jun 24 '16 at 14:28
  • I've dumped a variety of database result objects (never specifically a SQLite3Result) using this method. The output is always intelligible. However, your looping method gives fine control over how the file is structured. So, output buffering if you want a quick and dirty look at the data, looping if you want to use the file as input to another process or as a CSV or whatever. – Juan Tomas Jun 24 '16 at 14:31