0

我似乎无法弄清楚为什么我的表格数据不会出现在 csv 文件中。我有 1 页带有表单提交以启动导出过程。当我用 excel 打开文件时,我得到了正确的列标题...

谢谢您的帮助!!

if(isset ($_POST['submit'])) {
        $host = "";
        $user = "";
        $password = "";
        $db = "";
        $con = mysql_connect("$host", "$user", "$password") or die("Couldn't connect to server.");  
        $db = mysql_select_db("$db", $con) or die ("Couldn't select database.");
        $table = "wp_users";

    function exportMysqlToCsv($table,$filename = 'content.csv') {

    $csv_terminated = "\n";

    $csv_separator = ",";

    $csv_enclosed = '"';

    $csv_escaped = "\\";

    $query = "select * from $table";

    $result = mysql_query($query);

    $rowcount = mysql_num_fields($result);

    $data = '';

    for ($i = 0; $i < $rowcount; $i++) {

    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,

    mysql_field_name($result, $i)) . $csv_enclosed;

    $data .= $l;

    $data .= $csv_separator; }

    $output = trim(substr($data, 0, -1));

    $output .= $csv_terminated;

    while ($row = mysql_fetch_array($result)) {

    $data = '';

    for ($j = 0; $j < $fields_cnt; $j++) {

    if ($row[$j] == '0' || $row[$j] != '') {

    if ($csv_enclosed == '') { $data .= $row[$j]; }

    else { $data .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed; } }

    else { $data .= ''; }

    if ($j < $rowcount - 1) { $data .= $csv_separator; } }

    $output .= $schema_insert;

    $output .= $csv_terminated; }

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header("Content-Length: " . strlen($output));

    header("Content-type: text/x-csv");

    //header("Content-type: text/csv");

    //header("Content-type: application/csv");

    header("Content-Disposition: attachment; filename=$filename");

    echo $output;

    exit;

    } 

    exportMysqlToCsv($table);

    }
4

1 回答 1

0

问题似乎是您将 CSV 字符串分配给$data变量,但您没有将其附加到$output. 你需要这样一行:

$output .= $data;

就在之前:

$output .= $csv_terminated;

其次,我真的建议您修复代码结构。以现在的方式阅读代码非常困难。阅读PSR标准以获取更多信息(或有大量体面的标准)。

于 2013-06-08T03:58:27.583 回答