将查询输出到文本文件

时间:2011-05-18 13:04:31

标签: php mysql

我有这个代码(感谢stackoverflow的用户,我得到了我需要的标记:))。但是,我走上了一条我根本不了解的道路。我需要将这个格式化的查询表输出到服务器上的文本文件中。

<?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 "";
?>

我知道我可以使用与

类似的东西
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
?>

但我确信它不是最好的解决方案。所以我想我的问题是有人知道如何实现这个目标吗?

4 个答案:

答案 0 :(得分:0)

看看:

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

特别:

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

答案 1 :(得分:0)

这样的东西?

// 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

如果您需要数据库表的精确转储,则有更好的选项。 (实际上要好得多)。

答案 2 :(得分:0)

如果你想写一个文本文件,那么你建议的内容没有任何问题。

PHP手册中有很多信息:http://www.php.net/manual/en/ref.filesystem.php

这完全取决于您希望如何将数据存储在文件中。如果您愿意,可以创建自己的平面文件数据库格式,并在读入文件后使用PHP提取数据。

答案 3 :(得分:0)

最好的解决方案,特别是如果你的内存不足,就是把写作放到循环中:

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

请注意,我使用fputcsv以CSV格式输出数据(使用制表符作为分隔符)。这应该易于手动阅读,并且还可以通过例如电子表格程序容易地理解。如果您更喜欢自定义格式,则应在问题中使用fwrite