使用 php 和 ajax 生成并下载 CSV 文件

2023-12-26

我有一个php创建 CSV 文件的页面,然后浏览器会自动下载该文件。这是一个带有示例数据的版本 - 它效果很好。

<?php

$cars = array(
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csvfile.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Car', 'Year', 'Miles' ));

//Loop through the array and add to the csv
foreach ($cars as $row) {
    fputcsv($output, $row);
}

?>

我希望能够使用以下命令从另一个页面运行它ajax以便用户可以生成/下载csv无需离开主页。这是JavaScript我在主页上使用。在我的真实页面中,我使用通过 ajax 传入的数据。

$('button[name="exportCSVButton"]').on('click', function() {
    console.log('click');
    $.ajax({
        url: 'exportCSV.php',
        type: 'post',
        dataType: 'html',
        data: {

            Year: $('input[name="exportYear"]').val()
        },
        success: function(data) {
            var result = data
            console.log(result);


        }
    });
});

当我单击按钮触发脚本时,它会运行,但不会保存/下载到csv它将整个内容打印到控制台。有什么办法可以实现我想要的吗?无需实际将文件保存到服务器并重新打开。


我已经通过ajax下载了csv文件

PHP Code

    <?php
         function outputCsv( $assocDataArray ) {

            if ( !empty( $assocDataArray ) ):

                $fp = fopen( 'php://output', 'w' );
                fputcsv( $fp, array_keys( reset($assocDataArray) ) );

                foreach ( $assocDataArray AS $values ):
                    fputcsv( $fp, $values );
                endforeach;

                fclose( $fp );
            endif;

            exit();
        }

        function generateCsv(){
            $res_prods = $wpdb->get_results( "SELECT * FROM `{$wpdb->prefix}products` ", OBJECT );

            $products= [];
            foreach ($res_prods as $key => $product) :
                $product_id = $product->ID;

                $products[$product_id]['product_id'] = $product_id;
                $products[$product_id]['name'] = $product->name;
            endforeach;

            return outputCsv( $products);
      }

jQuery AJAX

jQuery(document).on( 'click', '.btn_generate_product', function(e) {

    var product_id = jQuery(this).data('product_id');

    jQuery.ajax({
        url : "ajaxurl", 
        type: 'POST',
        data: { product_id },
        success: function(data){

              /*
               * Make CSV downloadable
               */
              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "text/csv;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = "products.csv";

              /*
               * Actually download CSV
               */
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);

        }
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 php 和 ajax 生成并下载 CSV 文件 的相关文章

随机推荐