php - 将查询输出到文本文件

标签 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);
?>

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

最佳答案

最好的解决方案,尤其是在您内存不足的情况下,是将写入内容放入循环中:

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

相关文章:

php - 当 mkdir 从 PHP 失败时如何找到原因?

php - 如何使用ajax传递下拉选择的值并插入到mysql数据库中

mysql - 根据条件选择多于 1 列

mysql - 尝试更新表内容时出现语法问题 (MySQL Workbench)

php - 制作对象并将其传递到 codeigniter View

php - 从数据库中获取两个图像路径并将它们循环显示在 slider 中

php - 在 php 中文本到语音

php - 带有查询生成器的 Laravel 嵌套连接查询

php - 将搜索请求从我的网站转移到另一个网站

php - mysql查询中的if语句