微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在WordPress Admin中从PHP数组创建“下载到CSV”按钮

我已经使用函数填充了一个多维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)
        });

    });
});

解决方法:

继@charlietfl建议后,我发现“你不能通过Ajax来实现,因为JavaScript无法将文件直接保存到用户的计算机上(出于安全考虑).– According to this post

替代方案

我的替代解决方案是使用’post方法’来设置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

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐