fputcsv():提供的资源不是有效的流资源

时间:2019-02-04 06:57:47

标签: php arrays string csv fputcsv

我有以下代码;

我正在尝试使用以下代码生成csv,但这给了我错误:

fputcsv():提供的资源不是有效的流资源

// CSV column headings
$csv = Array
(
    "Card #, 
     Value of Card, 
     Current balance, 
     Amount used, 
     Transaction #,
     Transaction Date, 
     Ship To Name, 
     Ship To Address 1, 
     Ship To Address 2,
     Ship To Address 3, 
     Customer Telephone");

$csv [] = "2831013003939663, 
           0, 
           $1223.71, 
           $155.69,
           NULL,
           02-04-19_05:49:06,
           Demo demo,
           NULL,
           NULL,
           NULL,
           8108749624";


    $file = fopen("contacts.csv","w");
    foreach ($csv as $line)
      {
        fputcsv($file,explode(',',$line));
      }
    fclose($file);

我正在通过以下方式在调试中获得输出:

**

Array
(
    [0] => Card #,Value of Card,Current balance,Amount used,Transaction #,Transaction Date,Ship To Name,Ship To Address 1,Ship To Address 2,Ship To Address 3,Customer Telephone
    [1] => 2831013003939663,0,$1223.71,$155.69,-,02-04-19_05:49:06,Demo demo,-,-,-,8108749624
)

**

我不明白上面的代码在哪里出问题了?

2 个答案:

答案 0 :(得分:1)

尝试这样:

$arr=array("Card #,Value of Card,Current balance,Amount used,Transaction #,Transaction Date,Ship To Name,Ship To Address 1,Ship To Address 2,Ship To Address 3, Customer Telephone",
       "2831013003939663,0,$1259.64,$119.76,NULL,02-04-19_05:49:06,Demo demo,NULL,NULL, NULL,8108749624");


$filename = "contacts.csv";
$handle = fopen($filename, 'w+');

foreach($arr as $row) {
     $exploded_row=explode(',',$row);
     fputcsv($handle,$exploded_row);
}
fclose($handle);

答案 1 :(得分:0)

请注意,当您循环将数据放入 CSV 并在循环中执行 fclose() 而不是最后执行时,可能会发生这种情况。

例如:


    $handle = fopen($filename, 'w+');
    foreach(...){
    
        // Do something in the loop
        // Put Data in csv
        fputcsv($handle, $data);
    
        fclose($handle);
    }

现在,在这种情况下,第二次迭代将没有 $handle 流,因为它在第一次迭代结束时已经关闭。

应该是这样的:


    $handle = fopen($filename, 'w+');
    foreach(...){
    
        // Do something in the loop
        // Put Data in csv
        fputcsv($handle, $data);
    
    }
    
    // Closing after all actions on this CSV are done
    fclose($handle);