Anish Joshi
Anish Joshi

Reputation: 63

Export CSV is skipping first line of results

We have an online app built which our client can filter results from a table, and also export the results to CSV.

The trouble is when I export it to CSV it always skips the first line of the results.

Here is the code for the printcsv.php

$noheader = 1;
$protected = 1;

if(isset($_POST['query']) && $_POST['query'] != ''){
    $_GET['query'] = $_POST['query'];
}

if (isset($_GET['query'])){

    if(strpos($_GET['query'], 'limit')) {
        $_GET['query'] = substr($_GET['query'], 0, strpos($_GET['query'], 'limit'));
    }

    include('system/system.php');

    $results = SQLselectRA(stripslashes($_GET['query']));

    $x = 0;

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="printcsv.csv"');
    $file = fopen("php://output","w");
    $header = array();

    foreach($results as $keyvalue => $row) {    
        if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        $row = $header;
    }
    fputcsv($file, $row);
    $x++;
    }

If someone could help me out that would be great.

Regards

Upvotes: 1

Views: 921

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

You should write the header data using another variable than $row, which contained that first line of data, but that you're overwriting when you set the headers

foreach($results as $keyvalue => $row) {    
    if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        fputcsv($file, $header);
    }
    fputcsv($file, $row);
    $x++;
}

Upvotes: 2

Related Questions