Yaco Zaragoza
Yaco Zaragoza

Reputation: 437

PHP Export Array to CSV

I currently have a query that returns the array below.. When I try to export the data to a CSV file I see the data twice (The columns are repeted, not the rows).. Can someone explain to my why? (I want to have each records show only once)

Array
(
    [0] => Array
        (
            [0] => 6991
            [id] => 6991
            [1] => 8588
            [work_num] => 8588
            [2] => Test123
            [name] => Test123
            [3] => 1407154
            [deployed] => 1407154
            [4] => 2015-10-13
            [created_date] => 2015-10-13
        )
)

This is the code that I am using to export the data

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('id','Work Number','Name','Deployed','Date'));


$get_data  = $CLASSNAME->FuntionName(Parameters);

foreach($get_data as $data_row) {
    fputcsv($output, $data_row);
}

fclose($output);

Upvotes: 0

Views: 61

Answers (2)

clemens321
clemens321

Reputation: 2098

Either fix your incoming data (when using PDO, use PDO::FETCH_ASSOC or PDO::FETCH_NUM instead of PDO::FETCH_BOTH, which is default) or name your columns when putting to csv:

foreach($get_data as $data_row) {
    fputcsv($output, array(
        $data_row['id'],
        $data_row['work_num'],
        $data_row['name'],
        $data_row['deployed'],
        $data_row['created_date']
    ));
}

Upvotes: 1

Samir Selia
Samir Selia

Reputation: 7065

If you are using MySQL, then replace mysql_fetch_array to mysql_fetch_row.

mysql_fetch_array returns result set as both numeric and associative array. mysql_fetch_row will return result set as only numeric array.

Upvotes: 2

Related Questions