Php 将查询输出到文本文件

Php 将查询输出到文本文件,php,mysql,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());

我有这段代码,感谢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);
?>
但我相信这不是最好的解决办法。所以我想我的问题是,有人知道如何做到这一点吗?

看看:

特别是:

[INTO OUTFILE 'file_name' export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
像这样的

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

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

如果你想写一个文本文件,那么你的建议没有错

PHP手册中有很多信息:


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

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

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

请注意,我曾经使用选项卡作为分隔符以CSV格式输出数据。这应该是易于阅读的手,也将很容易理解,例如,电子表格程序。如果您喜欢自定义格式,您应该在问题中使用as。

为什么您确定这不是最佳解决方案-PHP编写文件您还需要什么?我尝试过,但它一直告诉我标题栏和所有内容都未定义。隐马尔可夫模型