开发者

Outputting Query to Textfile

I have this code (which thanks to the users of stackoverflow I got the markup I needed :) ). However, I have come to a road that I have no knowledge of what so ever. I need to output this formatted table of the query to a text file on the server.

<?php
// Make a MySQL Connection
 mysql_connect("hostname.net", "user", "pass") or die(mysql_error()); 
 mysql_select_db("database") or die(mysql_error()); 

// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM cards ORDER BY card_id") 
or die(mysql_error());  

echo "";
echo " Name AgeTitlebar ";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
    // Print out the contents of each row into a table
    echo ""; 
    echo $row['card_id'];
    echo ""; 
    echo $row['title'];
    echo ""; 
    echo $row['item_bar'];
    echo ""; 
} 

echo "";
?>

I know I could use something similar to

<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringDa开发者_如何学运维ta = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
?>

but I am sure that it cant be the best solution. So I guess my question is does anyone know how to achieve this?


The nicest solution, particularly if you are short on memory, would be to put the writing into the loop:

$fh = fopen('cards.csv', 'w');

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
    fputcsv($fh, array($row['card_id'], $row['title'], $row['item_bar']), "\t");
} 

fclose('cards.csv');

Note that I have used fputcsv to output the data in CSV format (using a tab as the delimiter). This should be easy to read by hand, and will also be easily understood by, for instance, a spreadsheet program. If you preferred a custom format, you should use fwrite as in your question.


Have a look at:

http://dev.mysql.com/doc/refman/5.0/en/select.html

especially:

[INTO OUTFILE 'file_name' export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]


Something like this?

// Make sure the file exists, do some checks.
// Loop trough result set and append anything to the file.
while (false !== ($aRow = mysql_fetch_assoc($rResult))) {
    $sCreateString = $aRow['field1'].';'.$aRow['field2'];
    file_put_contents('example.txt', $sCreateString, FILE_APPEND);
}
// Done

If you need an exact dump of the database table, there are better options. (much better actually).


If you want to write a text file, then there's nothing wrong with what you've suggested.

There's lots of information in the PHP manual: http://www.php.net/manual/en/ref.filesystem.php

It depends entirely on how you want to store the data inside the file. You can create your own flat-file database format if you wish, and extract the data using PHP once you've read in the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜