PHP数组到CSV
我正在尝试将一系列产品转换为CSV文件,但似乎没有计划。CSV文件是一长行,这是我的代码:
for($i=0;$i<count($prods);$i++) {$sql = "SELECT * FROM products WHERE id = '".$prods[$i]."'";
$result = $mysqli->query($sql);
$info = $result->fetch_array();
}
$header = '';
for($i=0;$i<count($info);$i++)
{
$row = $info[$i];
$line = '';
for($b=0;$b<count($row);$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;
}
此外,标头不会强制下载。我一直在复制并粘贴输出并保存为.csv
回答:
解决的问题:
如果有人在寻找相同的东西,请找到更好的方法:
$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");
回答:
与其写出值,不如考虑使用fputcsv()
。
这样可以立即解决您的问题。
以上是 PHP数组到CSV 的全部内容, 来源链接: utcz.com/qa/408471.html