如何在CSV文件中插入新行? [英] How to insert a new line into a CSV file?

查看:75
本文介绍了如何在CSV文件中插入新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个系统,其中涉及创建用于错误记录的CSV.

I am creating a system which involves the creation of a CSV for error logging.

我当前的代码成功创建了一个具有唯一名称的新文件,然后将现有数据(来自数组)添加到CSV中.我遇到的问题是在文件中添加新行,这是维持适当结构所必需的.

My current code successfully creates a new file with a unique name, then adds the existing data (from an array) into the CSV. The problem I'm having is adding new lines into the file, which is required to maintain proper structure.

我现有的代码:

$current = file_get_contents($fileName);
foreach($error as $err) {
    foreach($err as $title => $info) {
        $current .= $info . ',';
    }
    $current .= "\n";
}
file_put_contents($fileName, $current);

我的 $ error 数组结构的 var_dump 如下:

array (size=3)
  0 => 
    array (size=4)
      'id' => string '1' (length=6)
      'name' => string 'Kyle Katarn' (length=19)
      'qty' => string '1' (length=3)
      'date' => string '' (length=0)
  1 => 
    array (size=4)
      'id' => string '2' (length=6)
      'name' => string 'Dash Rendar' (length=23)
      'qty' => string '1' (length=2)
      'date' => string '' (length=0)
  2 => 
    array (size=4)
      'id' => string '3' (length=6)
      'name' => string 'Mara-Jade' (length=24)
      'qty' => string '1' (length=2)
      'date' => string '' (length=0)

我研究了各种不同的SO问题,但没有一个解决此问题.任何帮助将不胜感激.

I have looked on various different SO questions, and none has resolved this issue. Any help would be appreciated.

推荐答案

正如其他人所说,使用PHP_EOL生成新行.

As others have said, use PHP_EOL to generate a new line.

但是,我会自己使用 fputcsv 来确保内容正确封装:

However, I would use fputcsv myself to ensure the contents were correctly enclosed:

function generateCsv(array $data, $filename,  $delimiter = ',', $enclosure = '"') {
    $handle = fopen($filename, 'r+');
    foreach ($data as $line) {
        fputcsv($handle, $line, $delimiter, $enclosure);
    }
    rewind($handle);
    $contents = '';
    while (!feof($handle)) {
        $contents .= fread($handle, 8192);
    }
    fclose($handle);
    return $contents;
}

// usage
echo generateCsv($data, '/path/to/file.csv');

// or just save the csv to file:
generateCsv($data, '/path/to/file.csv');

此功能以及将csv保存到 $ filename 的功能,如果您喜欢 echo ,也会将生成的csv作为字符串返回.

This function, as well as saving the csv to $filename also returns the generated csv as a string if you fancy echoing it.

这篇关于如何在CSV文件中插入新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆