在 PHP 中将 CSV 写入不带括号的文件

发布于 2024-08-12 03:08:33 字数 374 浏览 4 评论 0原文

是否有本机函数或实体类/库用于将数组写入 CSV 文件中的一行而无需封装?如果没有为封装参数传入任何内容,fputcsv 将默认为 "。Google 让我失望了(返回有关 fputcsv 的一大堆页面的结果) >),PEAR 的库或多或少与 fputcsv 执行相同的操作,

其工作方式与 fputcsv 完全相同,但当前允许字段保持不带引号的状态

。 > 所需的“字段 1”、“字段 2”、field3hasNoSpaces

字段 1、字段 2、field3hasNoSpaces

Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsv will 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.

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

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

desired: field 1,field 2,field3hasNoSpaces

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

剩余の解释 2024-08-19 03:08:33

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

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

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

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");
愚人国度 2024-08-19 03:08:33

chr() 函数一起使用:

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

works with chr() function:

fputcsv($f,$array,',',chr(0));
北渚 2024-08-19 03:08:33

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

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

蝶…霜飞 2024-08-19 03:08:33
<?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',
);
<?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',
);
鲜肉鲜肉永远不皱 2024-08-19 03:08:33

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

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

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

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 :).

财迷小姐 2024-08-19 03:08:33

这行不通吗?

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

Doesn't this work?

fputcsv($fp, split(',', $line),',',' ');
七分※倦醒 2024-08-19 03:08:33

这就是我用来将标准 CSV 放入数组中的方法...

function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
        $resArr = array();
        $n = 0;
        $expEncArr = explode($enclose, $str);
        foreach($expEncArr as $EncItem){
                if($n++%2){
                        array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
                }else{
                        $expDelArr = explode($delim, $EncItem);
                        array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
                        $resArr = array_merge($resArr, $expDelArr);
                }
        }
        return $resArr;
} 

然后您可以在 foreach 循环中输出您想要的任何内容。

This is what I use to put standard CSV into an array...

function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
        $resArr = array();
        $n = 0;
        $expEncArr = explode($enclose, $str);
        foreach($expEncArr as $EncItem){
                if($n++%2){
                        array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
                }else{
                        $expDelArr = explode($delim, $EncItem);
                        array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
                        $resArr = array_merge($resArr, $expDelArr);
                }
        }
        return $resArr;
} 

You can then output whatever you want in a foreach loop.

Oo萌小芽oO 2024-08-19 03:08:33

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

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

?>

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.

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:

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

?>
难忘№最初的完美 2024-08-19 03:08:33

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

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

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

....
fputcsv($fp, $product_data,"\t");
....
shell_exec('sed -i \'s/"//g\' /path/to/your-file.txt ');
晨光如昨 2024-08-19 03:08:33

好的旧 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);

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

Whats wrong with good old 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)

蓝色星空 2024-08-19 03:08:33

根据您的应用选择解决方案。对于某些情况,需要自己的 csv 代码。对于情况 1(参见结果 chr0),情况 2(chr127) 和情况 3 (chr127) 数据将被修改(坏事)。相反,请使用类似的内容,谢谢@oops:

<?php
$fields = array("field 1","field 2","field3hasNoSpaces");
fputs(STDOUT, implode(',', $fields)."\n");
  • 情况 1。 fputcsv($f, $array, $delimiter, car(0)) 查看结果 chr0
  • 案例 2。fputcsv($f, $array, $delimiter, car(127))
    chr127
  • 案例 3. fputcsv($f, $array, $delimiter, ' ' )
    onespace
  • 案例 4. 自己的代码(s.above 的灵感来自
    哎呀
    Ansyori
    零和一)产生
    更好的结果。

Chose the solution depends on your application. For some case own code for csv is needed. In case 1 (See result chr0), case 2 (chr127) and case 3 (chr127) the data will be modified(bad thing). Instead use something like this, thanks @oops:

<?php
$fields = array("field 1","field 2","field3hasNoSpaces");
fputs(STDOUT, implode(',', $fields)."\n");
  • case 1. fputcsv($f, $array, $delimiter, car(0)) See result chr0
  • case 2. fputcsv($f, $array, $delimiter, car(127))
    chr127
  • case 3. fputcsv($f, $array, $delimiter, ' ')
    onespace
  • case 4. Own code (s.above inspired by
    oops or
    Ansyori or
    zeros-and-ones ) produces
    better results.
老子叫无熙 2024-08-19 03:08:33

chr(0) 也为我工作:

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

chr(0) also worked for me:

 fputcsv($fp, $aLine, $sDelimiter, chr(0));
蓬勃野心 2024-08-19 03:08:33

这是一个老问题,但由于我也在努力解决这个问题,我认为让任何正在寻找类似内容的人知道比你可以在 enclosure 参数中传递空字符串会更好fputcsv 的,它根本不会使用任何外壳。

IE

fputcsv($file, $array, ',', '');

This is an old question but as I was struggling with this as well, I thought it would be good to let anyone who is looking for something like this know than you can just pass empty string in the enclosure param of fputcsv and it will not use any enclosure at all.

i.e.

fputcsv($file, $array, ',', '');

半暖夏伤 2024-08-19 03:08:33

想通了。通过将 Null 的 ascii 代码传递给 car() 函数,它似乎工作得很好。

fputcsv($f, $array, $delimiter, car(0))

感谢大家的回答!

Figured it out. By passing in the ascii code for Null to the car() function it seems to work just fine.

fputcsv($f, $array, $delimiter, car(0))

Thanks for the answers everyone!!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文