将数据库表导出到csv文件(PHP脚本)

时间:2015-07-31 16:12:47

标签: php mysql csv

我想从我的数据库中导出一个表,其中包含一个列,其中我放置了大量文本内容,甚至包含许多段落。我已经测试了一个执行此工作的脚本,但是这个大型文本列存在一个特殊问题。当我运行脚本并导出csv文件时,大文本列只是在换行时拆分,并且它将所有这些换行作为文件中的新字段,因此csv文件就会崩溃。

我把我的代码放在这里。任何想法都将非常感激。

<?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;

?>

1 个答案:

答案 0 :(得分:1)

由于您使用的是mysql_ *,因此我不打算编辑该代码,因为该库已被弃用。您可以在此处使用我的个人代码,该代码使用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);
}
?>
相关问题