在PHP中查询mysql并将数据导出为CSV [英] Query mysql and export data as CSV in PHP
问题描述
我有myssql db与不同的表。表之间的数据被链接,我通过使用userid检索和显示它们。我使用了来自 PHP MYSQLi的参考资料显示数据库中的所有表
I have myssql db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from PHP MYSQLi Displaying all tables in a database
但是如何将此信息导出为csv文件?我已经尝试,而不是echo将其更改为一个字符串,并将该字符串打印到一个csv文件,但它不工作。
But how do I export this information as a csv file? I have tried instead of echo changed it to a string and print the string to a csv file but it is not working.
我也试过了例子:
http://sudobash.net/php-export-mysql- query-to-csv-file /
但我可以看到数据,但是顶部也有垃圾(如 ; font size ='1'>< table class ='xdebug-error xe-notice'dir ='ltr'border ='1'cellspacing ='0'cellpadding ='1'>$ c $
But I can see the data but on top there is also junk (like "<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>"
etc) inside the csv file.
有另一种方法吗?
推荐答案
如果要将每个MySQL行写入CSV文件,可以使用内置的PHP5函数 fputcsv
/ p>
If you want to write each MySQL row to a CSV file, you could use the built in PHP5 function fputcsv
$result = mysqli_query($con, 'SELECT * FROM table');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
这应该为写入 file.csv的每一行返回逗号分隔字符串
:
row1 val1, row1 val2
row2 val1, row2 val2
etc..
也请务必检查您正在写入的目录的权限。
Also be sure to check permissions for the directory you are writing to.
这篇关于在PHP中查询mysql并将数据导出为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!