将数据从CSV写入阵列到新CSV

时间:2021-01-20 21:35:41

I am trying to extract data from a CSV, run a function on some of it and spit it out into a new CSV. I'm getting stuck and writing the data to an array properly. Also, the file is created but its empty.

我正在尝试从CSV中提取数据,在其中运行一些函数并将其吐出到新的CSV中。我陷入困境并正确地将数据写入数组。此外,文件已创建但其为空。

PHP

PHP

$file = fopen("yahrzeit-3.csv","r");

if ($file) {
  while ( ( $row = fgetcsv( $file, ";" ) ) !== false ) { // 3

  $data .= array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );

}
print_r($data);
$fp = fopen('mailchimp.csv', 'w');

foreach ($data as $fields) {
    print $subfields;
    fputcsv($fp, $fields);
}
fclose( $fh ); // 5

}

fclose($fp);

2 个解决方案

#1


1  

$file = fopen("yahrzeit-3.csv","r");

if ($file) {
    $fp = fopen('mailchimp.csv', 'w');
    if (!$fp) {
        die('Cannot open output file');
    }
    while ( $row = fgetcsv( $file, ";" ) ) {
        $data = array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );
        fputcsv($fp, $data);
    }
    fclose( $fp );
}
fclose($file);

is a lot more memory efficient than what you're trying to do

比你想做的事情更有效

#2


0  

$data .= array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );

should be

应该

$data[] = array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );

You are setting $data as a string and trying to cram an array into it.

您将$ data设置为字符串并尝试将数组塞入其中。

#1


1  

$file = fopen("yahrzeit-3.csv","r");

if ($file) {
    $fp = fopen('mailchimp.csv', 'w');
    if (!$fp) {
        die('Cannot open output file');
    }
    while ( $row = fgetcsv( $file, ";" ) ) {
        $data = array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );
        fputcsv($fp, $data);
    }
    fclose( $fp );
}
fclose($file);

is a lot more memory efficient than what you're trying to do

比你想做的事情更有效

#2


0  

$data .= array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );

should be

应该

$data[] = array ( $row[2], $row[3], $row[6], $row[7], $row[8], $row[14] );

You are setting $data as a string and trying to cram an array into it.

您将$ data设置为字符串并尝试将数组塞入其中。