在 PHP 中将 CSV 写入没有附件的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1800675/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:53:18  来源:igfitidea点击:

Write CSV To File Without Enclosures In PHP

phpcsvquotesquoting

提问by Derek Reynolds

Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsvwill default to "if nothing is passed in for the enclosure param. Google is failing me (returning results for a whole bunch of pages about fputcsv), and PEAR's libraries do more or less the same things as fputcsv.

是否有本机函数或实体类/库用于在没有附件的 CSV 文件中将数组写入一行?如果没有为外壳参数传入任何内容,fputcsv则将默认为"。谷歌让我失望了(返回了一大堆关于 的结果fputcsv),而 PEAR 的库做的事情或多或少与fputcsv.

Something that works exactly like fputcsv, but will allow the fields to remain unquoted.

与 完全一样的东西fputcsv,但将允许字段保持不加引号。

currently: "field 1","field 2",field3hasNoSpaces

目前: "field 1","field 2",field3hasNoSpaces

desired: field 1,field 2,field3hasNoSpaces

期望: field 1,field 2,field3hasNoSpaces

回答by oops

The warnings about foregoing enclosures are valid, but you've said they don't apply to your use-case.

关于上述外壳的警告是有效的,但您已经说过它们不适用于您的用例。

I'm wondering why you can't just use something like this?

我想知道为什么你不能只使用这样的东西?

<?php
$fields = array(
    "field 1","field 2","field3hasNoSpaces"
);
fputs(STDOUT, implode(',', $fields)."\n");

回答by Michal - wereda-net

works with chr()function:

chr()函数一起使用:

fputcsv($f,$array,',',chr(0));

回答by Raul Duran

fputcsv($file, $data, ';', chr(127));

fputcsv($file, $data, ';', chr(127));

回答by Derek Reynolds

Well car(0)didn't work out as the NULLvalue will most likely choke most csv parsers.

好吧car(0)没有解决,因为该NULL值很可能会阻塞大多数 csv 解析器。

I ended using fputcsv()to build the initial file, then went through and removed all quotes. Elegant? Maybe not, but it got the job done :).

我结束使用fputcsv()来构建初始文件,然后通过并删除所有引号。优雅的?也许不是,但它完成了工作:)。

回答by Arthur Frankel

Doesn't this work?

这不行吗?

fputcsv($fp, split(',', $line),',',' ');

回答by zeros-and-ones

<?php       

$filename = "sample.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, ['column 1','column 2']);
$data = ['sample','data'];

fputs($handle, implode($data,',')."\n");

// or

fwrite($handle, implode($data,',')."\n");

fclose($handle);
$headers = array(
    'Content-Type' => 'text/csv',
);

回答by Ansyori

I use tricky way to remove double quote, but only in Linux

我使用棘手的方法删除双引号,但仅限于 Linux

....
fputcsv($fp, $product_data,"\t");
....
shell_exec('sed -i \'s/"//g\' /path/to/your-file.txt ');

回答by Matthew Fedak

Whats wrong with good old fwrite()?

好的旧 fwrite() 有什么问题?

function encloseString($field){
    return ($field) ? '"' . $field . '"' : null;
}

$delimiter = ';';
$data = ["data_field_1", "data_field_2", "data_field_3"];

$fp = fopen("some-file.csv", 'w');

for($i = 0;$i<100000;$i++) {
    fwrite($fp, implode($delimiter, array_map('encloseString', $data) . "\n");
}

fclose($fp);

(Obviously you need to make sure the data in $data is escaped first)

(显然你需要确保 $data 中的数据首先被转义)

回答by jb7AN

chr(0)also worked for me:

chr(0)也为我工作:

 fputcsv($fp, $aLine, $sDelimiter, chr(0));

回答by leepowers

The downside with a CSV file with no enclosures means an errant comma in user input will munge the row. So you'll need to remove commas before writing a CSV row.

没有附件的 CSV 文件的缺点意味着用户输入中的错误逗号将破坏该行。因此,您需要在写入 CSV 行之前删除逗号。

The tricky part with handling CSV is parsing enclosures, which makes the PHP & PEAR CSV functions valuable. Essentially you're looking for a file that is comma-delimited for columns and newline-delimited for rows. Here's a simple starting point:

处理 CSV 的棘手部分是解析附件,这使得 PHP 和 PEAR CSV 函数很有价值。本质上,您正在寻找一个以逗号分隔的列和换行符分隔的行的文件。这是一个简单的起点:

<?php
$col_separator= ',';
$row_separator= "\n";

$a= array(
 array('my', 'values', 'are', 'awes,breakit,ome'),
 array('these', 'values', 'also', "rock\nAND\nROLL")
);

function encodeRow(array $a) {
 global $col_separator;
 global $row_separator;
 // Can't have the separators in the column data!
 $a2= array();
 foreach ($a as $v) {
  $a2[]= str_replace(array($col_separator, $row_separator), '', $v);
 }
 return implode($col_separator, $a2);
}

$output= array();
foreach ($a as $row) {
 $output[]= encodeRow($row);
}

echo(implode($row_separator, $output));

?>