PHP 数组转 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13108157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Array to CSV
提问by JohnnyFaldo
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:
我正在尝试将一系列产品转换为 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;
}
Also, the header doesn't force a download. I've been copy and pasting the output and saving as .csv
此外,标题不会强制下载。我一直在复制和粘贴输出并保存为 .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");
采纳答案by Martin Lyne
回答by trank
This is a simple solution that exports an array to csv string:
这是一个将数组导出到 csv 字符串的简单解决方案:
function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
return stream_get_contents($f);
}
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));
回答by Martyn Shutt
Try using;
尝试使用;
PHP_EOL
To terminate each new line in your CSV output.
终止 CSV 输出中的每个新行。
I'm assuming that the text is delimiting, but isn't moving to the next row?
我假设文本正在分隔,但不会移动到下一行?
That's a PHP constant. It will determine the correct end of line you need.
这是一个 PHP 常量。它将确定您需要的正确行尾。
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
例如,Windows 使用“\r\n”。当我的输出没有中断到新的一行时,我用那个绞尽脑汁。
回答by J nui
I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that. I used a string as output, as implode can't add new line (new line is something I added, and should really be there).
我知道这是旧的,我有一个案例,我也需要将数组键包含在 CSV 中,所以我更新了 Jesse Q 的脚本来做到这一点。我使用了一个字符串作为输出,因为 implode 不能添加新行(新行是我添加的,应该真的存在)。
Please note, this only works with single value arrays (key, value). but could easily be updated to handle multi-dimensional (key, array()).
请注意,这只适用于单值数组(key, value)。但可以轻松更新以处理多维(key, array()).
function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = '';
foreach ( $fields as $key => $field ) {
if ($field === null && $nullToMysqlNull) {
$output = '';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output .= $key;
$output .= $delimiter;
$output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
$output .= PHP_EOL;
}
else {
$output .= $key;
$output .= $delimiter;
$output .= $field;
$output .= PHP_EOL;
}
}
return $output ;
}
回答by Avraham Markov
Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php
数据数组通过内置的 php 函数 fputcsv 转换为 csv 'text/csv' 格式,用于处理逗号、引号等。
查看
https://coderwall.com/p/zvzwwa/array-to-comma-separated -string-in-php
http://www.php.net/manual/en/function.fputcsv.php
回答by Jesse Q
In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:
就我而言,我的数组是多维的,可能以数组作为值。所以我创建了这个递归函数来完全分解数组:
function array2csv($array, &$title, &$data) {
foreach($array as $key => $value) {
if(is_array($value)) {
$title .= $key . ",";
$data .= "" . ",";
array2csv($value, $title, $data);
} else {
$title .= $key . ",";
$data .= '"' . $value . '",';
}
}
}
Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:
由于我的数组的各个级别不适合平面 CSV 格式,因此我创建了一个带有子数组键的空白列,作为对下一级数据的描述性“介绍”。示例输出:
agentid fname lname empid totals sales leads dish dishnet top200_plus top120 latino base_packages
G-adriana ADRIANA EUGENIA PALOMO PAIZ 886 0 19 0 0 0 0 0
You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:
您可以轻松删除“介绍”(描述性)列,但在我的情况下,我在每个子数组中都有重复的列标题,即 inbound_leads,因此在下一部分之前给了我一个中断/标题。消除:
$title .= $key . ",";
$data .= "" . ",";
after the is_array() to compact the code further and remove the extra column.
在 is_array() 之后进一步压缩代码并删除额外的列。
Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:
因为我想要标题行和数据行,所以我将两个变量传递给函数,并在完成对函数的调用后,用 PHP_EOL 终止它们:
$title .= PHP_EOL;
$data .= PHP_EOL;
Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.
是的,我知道我留下了一个额外的逗号,但为了简洁起见,我没有在这里处理它。

