PHP导出到CSV文件的前两行为空

时间:2015-10-27 02:37:17

标签: php

我在数组中有以下数据,并且想要写入CSV文件。除了我在.csv文件中看到前两个空行

之外,一切正常

感谢任何帮助......再次感谢!!!!

CSV文件中的输出如下     空Line1
    空Line2
    ip address ip state description hostmane mac owner device notes     数据......

数组数据:

Array (
[0] =>Array ( [ip address] => 1.3.2.1 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => ) 
[1] =>Array ( [ip address] => 1.3.2.2 [ip state] => Reserved [description] => [hostname] => linux [mac] => [owner] => test [device] => Linux Server [note] => Linux123 )
[2] => Array ( [ip address] => 1.3.2.3 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => )
[3] => Array ( [ip address] => 1.3.2.4 [ip state] => Active [description] => [hostname] => [mac] => [owner] => [device] => [note] => )
)  

用于写入CSV文件的PHP函数是:

switch("export-to-csv")
{   
    case "export-to-csv" :
        // Submission from
        $filename = $_GET["exformat"] . ".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Expires: 0");
        ExportCSVFile($data);
        //$_GET["exformat"] = '';
        exit();
    default :
        die("Unknown action : ".$_POST["action"]);
        break;
}

function ExportCSVFile($records) {
    // create a file pointer connected to the output stream 
    #print_r ($records); return;
    $fh = fopen( 'php://output', 'w' );
    $heading = false;
    if(!empty($records)) {
        foreach($records as $row) {            
            if(!$heading)  {
              // output the column headings
              fputcsv($fh, array_keys($row));
              $heading = true;
            }
        // loop over the rows, outputting them
         fputcsv($fh, array_values($row));              
      }       

    }
}

2 个答案:

答案 0 :(得分:0)

请使用框架的index.php或开头有空行的任何其他文件中的任何文件,这可能会导致csv中出现空行。

答案 1 :(得分:0)

请检查您在函数调用之前包含的其他文件以及哪些文件具有打印空间等。您可以检查使用记事本在记事本中打开导出的csv文件,您可以看到是否有空格您的PHP代码是否正常工作完美没有任何问题。我用波纹管阵列测试了它的工作正常。

--add-host=dockerhost:replace_with_docker_host_ip