通过PHP从MySQL导出到CSV

时间:2015-10-29 11:01:02

标签: php mysql csv

我正在尝试修复一个PHP脚本,该脚本应该将值从MySQL数据库导出到CSV文件。

PHP文件返回一个空白的CSV文件&我无法弄清楚为什么&我已经坚持了很长一段时间,所以任何帮助都会受到很大影响。

以下代码:

<?
include('../../../inc/config.php');
$period = $_GET['pid'];

$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];

$query="SELECT
    sid,
    date,
    stove_id,
    name,
    gender,
    marital_status,
    occupation_of_household,
    cz_stove AS km_stove,
    happy_with_cz_stove AS happy_with_km_stove,
    cz_stove_in_use AS km_stove_in_use,
    know_how_to_use,
    FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
  //header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
    echocsv(array_keys($row));
}
while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}

?>

3 个答案:

答案 0 :(得分:0)

问题是您在打开csv文件之前没有写任何内容。

使用此代码

    $fp = fopen($filename, 'w');
    $result = mysql_query($query);

    $num_fields = mysql_num_fields($result);
    $headers = array();
    for ($i = 0; $i < $num_fields; $i++) {
        $headers[] = mysql_field_name($result , $i);
    }

    fputcsv($fp, $headers); 

    while($row = mysql_fetch_assoc($result)) {
        fputcsv($fp, $row); 
    }
    fclose($fp);


    header('Content-Type: text/csv');
    header( "Content-disposition: filename=".$filename);
    readfile($filename);

答案 1 :(得分:0)

hey i have a code you can use it like this

    <?PHP

// Define  database connection variable dynamically
$DB_Server = "localhost";           //MySQL Server    
$DB_Username = "root";              //MySQL Username     
$DB_Password = "";                  //MySQL Password     
$DB_DBName = "test1";    //MySQL Database Name  
$DB_TBLName = "tabletest";          //MySQL Table Name   
$filename = "excelfilename";        //File Name
//create MySQL connection   
$sql = "Select * from csvtable";
$Connect = @mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database   
$Db = @mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query 
$result = @mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );

function cleanData(&$str) 
{
    if ($str == 't')
        $str = 'TRUE';
    if ($str == 'f')
        $str = 'FALSE';
    if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
        $str = "'$str";
    }
    if (strstr($str, '"'))
        $str = '"' . str_replace('"', '""', $str) . '"';
}

// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;

while ($row = mysqli_fetch_assoc($result))
{
    if (!$flag) 
        {
        // display field/column names as first row 
        fputcsv($out, array_keys($row), ',', '"'); $flag = true; 
        }
    array_walk($row, 'cleanData');
    // insert data into database from here
    fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>

答案 2 :(得分:0)

感谢大家的建议,问题现在已经解决了,原来是一个简单的逗号在错误的地方 - &#34; know_how_to_use,&#34;改为&#34; know_how_to_use&#34;解决了这个问题。谢谢@Tintu C Raju指出我正确的方向