php中实现将mysql导出成csv文件,在PHP中查询mysql并将数据导出为CSV

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

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.

But I can see the data but on top there is also junk (like "

etc) inside the csv file.

Is there another way to do this?

解决方案

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

Which should return a comma separated string for each row written to file.csv:

row1 val1, row1 val2

row2 val1, row2 val2

etc..

Also be sure to check permissions for the directory you are writing to.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值