0

I am getting all the values from the database as an array. As its a huge database I am just showing two rows for reference.

So the array goes like this by doing 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
        )        
)

Now I want to export is as csv. So I made my php code like this

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");

Now when I opened the csv I saw that if in a row there is no data for a column then the next column just doing shift to one step back. Like this

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

As you can see the data is shifting to the previus column in 2nd and 3rd row. So can someone tell me how to solve this. Sorry but I can't change the database. Any help and suggestions wil be really appreciable. Thanks

NewUser
  • 11,759
  • 36
  • 127
  • 221

0 Answers0