fput csv没有添加第二行

时间:2017-06-21 14:38:27

标签: php csv

有人可以看到这段代码有什么问题吗? $ output是一个多维数组,因此我将其展平,然后将Keys和Values拆分为单独的数组。我已经完成了$ header和$ answers的var_dump,但出于某种原因fputscsv($buffer, $answers)没有做任何事情。标题显示正常,因此该行周围的某些内容正在破坏:/

function buildcsv($output)
{
  $headers = array();
  $answers = array();

  foreach($output as $section) // Flatten sections into single array and remove config rows.
  {
     array_shift($section);
     array_pop($section);
     array_pop($section);

     foreach($section as $question => $answer)
     {
       array_push($headers, $question); // Build array for header row
       array_push($answers, $answer); // Build array for answers row
     }
  }

     array_push($headers, "Read terms and conditions"); // Add terms and consitions column.
     array_push($answers, "Yes");

     $buffer = fopen('php://temp', 'r+');
     fputcsv($buffer, $headers);
     fputcsv($buffer, $answers);
     rewind($buffer);
     $csv = fgets($buffer);
     fclose($buffer);
     return $csv;

 }

2 个答案:

答案 0 :(得分:0)

不确定,但写一下可能会更好:" php://temp/file.csv" ?

答案 1 :(得分:0)

因此,基于我似乎只是出于某种原因才能正确访问输出缓冲区的事实,这就是我想出的。该函数允许另一个代码块将表单的rsponse转换为CSV格式,然后将其附加到电子邮件中。

// Generate csv
 function buildcsv($output)
 {
     $headers = array();
     $answers = array();

     foreach($output as $section) // Flatten sections into single array and remove config rows.
     {
        array_shift($section);
        array_pop($section);
        array_pop($section);
        foreach($section as $question => $answer)
        {
                array_push($headers, $question); // Build array for header row
                array_push($answers, $answer); // Build array for answers row
        }
     }

     array_push($headers, "Read terms and conditions"); // Add terms and conditions column.
     array_push($answers, "Yes");

     $buffer = fopen('php://output', 'r+');

     ob_start();

     fputcsv($buffer, $headers);
     fputcsv($buffer, $answers);

     rewind($buffer);
     $csv = ob_get_contents();

     ob_end_clean();
     return $csv;

 }