Lucarolina
Lucarolina

Reputation: 33

Export Database table to csv file (PHP script)

I want to export a table from my database, which contains a column where I put large text content, even many paragraphs. I've tested a script that does this work, but it has a special problem with this large text column. When I run the script and it exports the csv file, large text column just splits when there's a line break, and it takes all these line breaks as new fields inside the file, so csv file just breaks down.

I put my code here. Any ideas would be very appreciated.

<?php

// Database Connection

$host="localhost";
$uname="*****";
$pass="*****";
$database = "****"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be     selected");  
$result=mysql_select_db($database)
or die("database cannot be selected <br>");


// Fetch Record from Database

$output         = "";
$table          = "table"; // Enter Your Table Name
$sql            = mysql_query("SELECT * FROM $table");
$columns_total  = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
    $heading    =   mysql_field_name($sql, $i);
    $output     .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename =  "file.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>

Upvotes: 2

Views: 2515

Answers (1)

Akshay
Akshay

Reputation: 2229

Since you're using mysql_*, I'm not going to edit that code, since the library is deprecated. You can use my personal code here which uses PDO.

<?php
include 'dbconnector.php';
$array = array();

# Headers
$array[] = array("header1", "header2");
$serial=1;
try
{
    $s = $conn->query("Query Here");
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
while($donations = $s->fetch(PDO::FETCH_OBJ))
{
    $array[] = array("column1","column2"); 
}

array_to_csv_download($array,"records.csv",",");

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // rewrind the "file" with the csv lines
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachement; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}
?>

Upvotes: 1

Related Questions