php 数组导出csv_PHP数组到CSV

I'm trying to convert an array of products into a CSV file, but it doesn't seem to be going to plan. The CSV file is one long line, here is my code:

for($i=0;$i

$sql = "SELECT * FROM products WHERE id = '".$prods[$i]."'";

$result = $mysqli->query($sql);

$info = $result->fetch_array();

}

$header = '';

for($i=0;$i

{

$row = $info[$i];

$line = '';

for($b=0;$b

{

$value = $row[$b];

if ( ( !isset( $value ) ) || ( $value == "" ) )

{

$value = "\t";

}

else

{

$value = str_replace( '"' , '""' , $value );

$value = '"' . $value . '"' . "\t";

}

$line .= $value;

}

$data .= trim( $line ) . "\n";

}

$data = str_replace( "\r" , "" , $data );

if ( $data == "" )

{

$data = "\n(0) Records Found!\n";

}

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=your_desired_name.xls");

header("Pragma: no-cache");

header("Expires: 0");

array_to_CSV($data);

function array_to_CSV($data)

{

$outstream = fopen("php://output", 'r+');

fputcsv($outstream, $data, ',', '"');

rewind($outstream);

$csv = fgets($outstream);

fclose($outstream);

return $csv;

}

Also, the header doesn't force a download. I've been copy and pasting the output and saving as .csv

EDIT

PROBLEM RESOLVED:

If anyone else was looking for the same thing, found a better way of doing it:

$num = 0;

$sql = "SELECT id, name, description FROM products";

if($result = $mysqli->query($sql)) {

while($p = $result->fetch_array()) {

$prod[$num]['id'] = $p['id'];

$prod[$num]['name'] = $p['name'];

$prod[$num]['description'] = $p['description'];

$num++;

}

}

$output = fopen("php://output",'w') or die("Can't open php://output");

header("Content-Type:application/csv");

header("Content-Disposition:attachment;filename=pressurecsv.csv");

fputcsv($output, array('id','name','description'));

foreach($prod as $product) {

fputcsv($output, $product);

}

fclose($output) or die("Can't close php://output");

解决方案

Instead of writing out values consider using fputcsv().

This may solve your problem immediately.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值