使用PHP MySQL创建CSV时,会在开头插入一行空行


A blank line is inserted at the beginning when Creating CSV using PHP MySQL

我正在尝试将MySQL表的内容获取到CSV文件中。除了在我通过Array的标题标签之前插入一个空行之外,一切都很好。

 <?php
    error_reporting(0);
    ob_start();
    session_start();
    include 'auto_logout.php';
    //echo $_SESSION['fullname'];
    if ((!isset($_SESSION['ufullname'])) && (!isset($_SESSION['fullname']))) {
        /* Redirect browser */
        header("Location: index.php");
        /* Make sure that code below does not get executed when we redirect. */
        exit();
    }
    $output = "";
    require_once('config/config.php');
    require_once("includes/ftp_settings.php");
    $table = "Download CSV"; // Enter Your Table Name 
    if (is_array($new_exist) && (is_array($ftp1))) {
        $ressd_new = 'select filename from files where uploaded_by IN ("' . implode('","', $new_exist) . '")';
        $resd_new  = mysql_query($ressd_new);
        while ($kkk_new = mysql_fetch_array($resd_new)) {
            $gotit_new = $kkk_new[0];
        }
        $resultka_new = $ftp1;
        $sql = 'SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where uploaded_by IN ("' . implode('","', $new_exist) . '") and filename IN ("' . implode('","', $resultka_new) . '") and size != "0"';
    } else {
        $sql = "SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where ftp_file  = '$ftp_server' and ftp_u_file = '$ftp_user_name' and ftp_p_file = '$ftp_user_pass' and size != '0'";
    }
    $sql           = mysql_query($sql);
    $columns_total = mysql_num_fields($sql);
    // Get The Field Name
    $heading1 = array(
        "Sl. No.",
        "File Name",
        "Uploaded By",
        "Date Added",
        "Time Added",
        "Size"
    );
    $inc = 0;
    for ($i = 0; $i < $columns_total; $i++) {
        $heading = $heading1[$inc];
        $output .= '"' . $heading . '",';
        $inc = $inc + 1;
    }
    $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 = "myFile.csv";
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
    echo $output;
    exit;
?>

不太确定空行是从哪里来的。

如果处理不当,包含文件通常会添加不需要的空白。在任何情况下,抑制错误都会使情况变得更糟。

您需要ob_start()的原因是,ob_start()和"echo$output;"之间的脚本正在打印一些内容(可能是空行)。因此,您无法设置标题。我敢打赌它在您包含的文件中(auto_loop、config、ftp_settings)。

允许错误,删除ob_start,解决所有警告,获利。

顺便说一句:不要使用mysql扩展,而是使用mysqli。