当没有数据时,php导出到csv正在移动列

时间:2015-06-02 11:39:38

标签: php csv fputcsv

我从数据库中获取所有值作为数组。作为一个庞大的数据库,我只是展示了两行供参考。

所以数组就是这样做print_r($data);

array(
    [0] => Array
        (
            [listing_id] => 5975
            [category_id] => A la Carte|Bar|Banquet|Champagne Bar|Cajun Creole|German
            [listing_name] => test-chris
            [image_name] => SBCTR Logo.jpg
            [address] => 1 surfe parade
            [phone] => 0402331482
        )

    [1] => Array
        (
            [listing_id] => 5974
            [category_id] => 
            [listing_name] => Charlie Lovett
            [image_name] => SBCTR Logo.jpg
            [address] =>  
            [phone] => 
        )

    [2] => Array
        (
            [listing_id] => 5973
            [category_id] => Banquet|Champagne Bar
            [listing_name] => Charlie Lovett
            [image_name] => SBCTR_1234 Logo.jpg
            [address] =>  
            [phone] => 1231234567
        )        
)

现在我要导出为csv。所以我制作了像这样的PHP代码

function export_to_csv($data, $filename="data.csv", $delim = ',', $newline = "\n", $enclosure = '' ) {
   $string_to_export = '';
   $c = 0;
   foreach( $data as $row) {
    $string_to_export .= $enclosure.implode($enclosure.$delim.$enclosure, ( $c ? array_values($row) : array_keys($row)) ).$enclosure.$newline; 
    $c++;
    }
        header('Content-type: text/csv;charset=utf-8');
        header('Content-Disposition: attachment; filename='.$filename);
        header("Cache-Control: no-cache");
        //echo "\xEF\xBB\xBF";
    echo $string_to_export;
    exit();
 }
 export_to_csv($data, "data.csv");

现在,当我打开csv时,我看到如果连续没有列的数据,那么下一列只是转移到后退一步。喜欢这个

listing_id    category_id               listing_name        image_name          address          phone

 5975         A la Carte|Bar....        test-chris          SBCTR Logo.jpg      1 surfe parade   1482

 5974         Charlie Lovett            SBCTR Logo.jpg

 5973         Banquet|Champagne Bar    Charlie Lovett       SBCTR_1234 Logo.jpg  1231234567

正如您所看到的,数据正在转移到第2行和第3行的previus列。那么有人可以告诉我如何解决这个问题。抱歉,我无法更改数据库。任何帮助和建议都会非常明显。感谢

0 个答案:

没有答案