Jovel Mark Diaz
Jovel Mark Diaz

Reputation: 23

Wordpress export data from database to csv using $wpdb

I am stuck with this problem, i have a code to insert the data to database, and query it all at the wordpress page. then i want to export it in csv, but i dont know how to do it. i have codes found on internet but not working. i dont know why, please check my codes. this is my codes..

 global $wpdb;
    if(isset($_POST["Export"])){
    $result = $wpdb->get_results('SELECT * FROM backend_member', ARRAY_A);

    header('Content-Type: text/csv');
    $date = date("Y-m-d H:i:s");
    header('Content-Disposition: attachment;filename=EXPORT_' . $date . '.csv');

    foreach ($result as $row) {
        if ($row) {
            exportCsv(array_keys($row));
        }}
    while ($row) {
        foreach ($result as $row) {
                exportCsv($row);
        }}
    function exportCsv($rows) {
        $separator = '';
        foreach ($rows as $row) {
            echo $separator . $row;
            $separator = ',';
        }
        echo "\r\n";
    }
}

<div><form class="form-horizontal" action="" enctype="multipart/form-data" method="post" name="upload_excel">
<div class="form-group">
<div class="col-md-4 col-md-offset-4"><input class="btn btn-success" name="Export" type="submit" value="export to excel" /></div>
</div>
</form></div>

When i click export. i have an error.

This site can’t be reached

The webpage at http://www.rimelig-skat.dk/din-admin/ might be temporarily down or it may have moved permanently to a new web address.
ERR_INVALID_RESPONSE

Upvotes: 1

Views: 5384

Answers (1)

Bhumi Shah
Bhumi Shah

Reputation: 9466

Here is updated code:

global $wpdb;
if(isset($_POST["Export"])){
    $filename = 'test';
    $date = date("Y-m-d H:i:s");
    $output = fopen('php://output', 'w');
    $result = $wpdb->get_results('SELECT * FROM     tp_users', ARRAY_A);
    fputcsv( $output, array('ID', 'Title', ' Date'));
    foreach ( $result as $key => $value ) {
        $modified_values = array(
                        $value['ID'],
                        $value['user_login'],
                        $value['user_email']
        );
        fputcsv( $output, $modified_values );
    }
    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; charset=utf-8');
    // header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $filename . " " . $date . ".csv\";" );
    // header('Content-Disposition: attachment; filename=lunchbox_orders.csv');
    header("Content-Transfer-Encoding: binary");exit;
}

HTML

<div><form class="form-horizontal" action="" enctype="multipart/form-data" method="post" name="upload_excel">

This code is perfectly working fine in my wordpress.

Upvotes: 4

Related Questions