WordPress一键导出数据表到CSV文件

functions.php中增加代码如下:

function csv_pull_tables()
{
    global $wpdb;
    $file = 'table_csv';
    $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}tables;", ARRAY_A);

    if (empty($results)) {
        return;
    }

    $csv_output = '"'.implode('","', array_keys($results[0])).'"'."\n";

    foreach ($results as $row) {
        $csv_output .= '"'.implode('","', $row).'"'."\n";
    }
    $csv_output .= "\n";

    $filename = $file."_".date("Y-m-d_His", time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header("Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    exit;
}
add_action('wp_ajax_csv_tables', 'csv_pull_tables');

通过admin_url('admin-ajax.php?action=csv_pull');生成的链接地址即可直接下载CSV文件。

304 total views, 2 views today

Revisions

There are no revisions for this post.

No comments yet.

发表评论