当使用标头输出到csv时,回显到屏幕


Echoing to screen when using headers to output to csv

我有一个PHP应用程序,它生成一组代码,将它们保存到MySQL DB,然后将其作为可下载的csv文件输出给用户。在代码块之后,我还使用echo语句将PHP数组转换为csv。convert_to_csv函数调用后的echo语句不是输出到浏览器,而是输出到文件并覆盖第一行。如何将echo语句输出到浏览器呢?代码块在下面:

convert_to_csv($newCodesArray,$fileName,',');
echo "Your file was successfully generated";
function convert_to_csv($input_array, $fileName, $delimiter)
{
    header('Content-Type: text/csv');
    header("Content-Disposition: attachment; filename='"$fileName'"");
    $f = fopen('php://output', 'w');
    /* loop through array  */
    foreach ($input_array as $line) {
        /* default php csv handler */
        fputcsv($f, $line, $delimiter);
    }
    fclose($f) or die("Can't close php://output");
}

您已经将标题定义为text/csv。所以它不会在浏览器中打印,因为它需要text/html。

或者,您可以按以下方式操作。将函数复制到另一个文件(例如csv.php)。

<?php 
echo "Your file was successfully generated <script> window.location = 'csv.php' </script>";

现在它将打印您的echo字符串并开始下载您的csv文件。

正如Magnus Eriksson所评论的,

上面的代码没有检查它是否真的生成成功。我们可以用AJAX扩展代码。
    <script>
     $.ajax('csv.php', {
      success: function(data) {
         document.write('Your file was successfully generated.');
         windows.location = 'csv.php';
      },
      error: function() {
         document.write('Your file generation failed.');
      }
     });
   </script>

注意:- AJAX调用将生成文件两次。