我有这段代码(多亏了 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);
?>
但我确信这不是最佳解决方案。所以我想我的问题是有人知道如何实现这一目标吗?
最佳答案
最好的解决方案,尤其是在您内存不足的情况下,是将写入内容放入循环中:
$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
正如你的问题。
关于php - 将查询输出到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6045141/