【问题标题】:Create 'Download to CSV' button from PHP array in Wordpress Admin在 Wordpress Admin 中从 PHP 数组创建“下载到 CSV”按钮
【发布时间】:2018-02-18 11:36:25
【问题描述】:

我使用函数填充了一个多维 PHP 数组,我希望允许我的管理员用户下载内容。

我找到了一个 PHP 函数,它应该允许我将数组导出为 CSV 并将其放入我的 functions.php,使用第二个函数将其连接到 AJAX 并使用 jQuery 来触发 AJAX 函数。

有什么问题?

所以我 99% 确定 AJAX 正确地发布到 PHP 函数,但由于某种原因,下载没有开始。

我对此进行了很多研究,但一直在努力寻找解决方案 - 非常感谢您指出正确的方向!

// Function to generate download

function convert_to_csv( $input_array, $output_file_name, $delimiter ) {
    /** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
    $f = fopen( 'php://memory', 'w' );
    /** loop through array  */
    foreach ( $input_array as $line ) {
        /** default php csv handler **/
        fputcsv( $f, $line, $delimiter );
    }
    /** rewrind the "file" with the csv lines **/
    fseek( $f, 0 );
    /** modify header to be downloadable csv file **/
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachement; filename="' . $output_file_name . '";' );
    /** Send file to browser for download */
    fpassthru( $f );
}

我已经使用另一个函数将它连接到 Wordpress AJAX

function laura_function() {

    $input_array = $_POST["inputarray"];

    convert_to_csv($input_array, 'output.csv', ',');

    exit;

}
add_action('wp_ajax_nopriv_ajaxlaurafunction', 'laura_function');
add_action('wp_ajax_ajaxlaurafunction', 'laura_function');

我写了一个小的 jQuery 函数来在按钮点击时进行 AJAX 调用

<button type="button" id="downloadcsv">Download CSV</button>

<script>

    jQuery(document).ready(function () {
        jQuery('#downloadcsv').click(function () {

        var data = {
            action: 'ajaxlaurafunction', // Calls PHP function - note it must be hooked to AJAX
           inputarray: '<?php echo $inputarray?>', // Sends a variable to be used in PHP function
        };

        // This is a shortened version of: https://api.jquery.com/jquery.post/

        jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function () {
            //window.location.replace(location.pathname)
        });

    });
});

【问题讨论】:

  • ajax 和下载是不同的概念。在搜索中使用这两个词进行一些研究
  • charlietfl - 好的。感谢您的指点。 @用户8262086。谢谢 :)。我现在已经为这个答案发布了一个不使用 AJAX 的解决方案。我会对你的 cmets 感兴趣。

标签: javascript php jquery ajax wordpress


【解决方案1】:

根据@charlietfl 的建议,我发现“你不能通过 Ajax 来做到这一点,因为 JavaScript 不能将文件直接保存到用户的计算机上(出于安全考虑)。- According to this post

替代解决方案

我的替代解决方案是使用“发布方法”来设置发布参数。

// Form on Page 
<form method="post" id="download_form" action="">
    <input type="submit" name="download_csv" class="button-primary" value="Download CSV" />
</form>

如果已发布“download_csv”参数,则此代码运行以下载数据。目前我的代码将输出虚拟数据,但我正在努力。

add_action("admin_init", "download_csv");

function download_csv() {

if (isset($_POST['download_csv'])) {

    function outputCsv( $fileName, $assocDataArray ) {
        ob_clean();
        header( 'Pragma: public' );
        header( 'Expires: 0' );
        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
        header( 'Cache-Control: private', false );
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename=' . $fileName );
        if ( isset( $assocDataArray['0'] ) ) {
            $fp = fopen( 'php://output', 'w' );
            fputcsv( $fp, array_keys( $assocDataArray['0'] ) );
            foreach ( $assocDataArray AS $values ) {
                fputcsv( $fp, $values );
            }
            fclose( $fp );
        }
        ob_flush();
    }

    // This is dummy data. 

    $data = array(
        array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe' ),
        array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John' ),
        array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James' ),
    );


    outputCsv( 'expenses.csv', $data );

    exit; // This is really important - otherwise it shoves all of your page code into the download

}

}

【讨论】:

  • 你会用什么动作钩子让它在前端工作?对于想要 DL 数据集的用户?
  • @user1518699 尝试“初始化”。
  • 这是一个很好的答案
  • 这个很好,用于导出我创建的自定义 WP_List_Table。
  • 我正在做几乎完全相同的事情,但是在 wordpress 前端页面上..用户可以将他们的数据下载到 csv 文件中。但它确实将页面代码推入文件中,即使我调用 exit。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
相关资源
最近更新 更多