adi
adi

Reputation: 479

Create csv file from mysql results with php?

So I'm trying to make a .csv file which after I will download it,but the problem is that the rows are not going aranging properly. I am using fputcsv.

$tot.="$codcomanda,$clientnume,$brandnume,$numeprod,$um,$cantitate,$updatare";
$list =array(
    array('Comanda','Client','Categorie','Produs','UM','Cantitate','Actualizare'),
    array($tot),
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

The variable $tot is from a while statement and it gets its variable from different queries and I cannot find a php code on the internet that is for my needs.I've tried several ways to try and make it work but nothing. I've tried making $tot different ways but none work,either it $tot.= The csv file should have something like.

But my csv shows like

I've tried making $tot different ways but none work,either the csv show like this or doesn't display no content at all.


Solved: Using fwrite i've solved it.

$tot.="$codcomanda;$clientnume;$brandnume;$numeprod;$um;$cantitate;$updatare;\n";
$tot2="Comanda;Client;Brand;Produse;U.M;Cantitate;Actualizare;\n$tot";

    $file = fopen("file.csv","w");
    fwrite($file,$tot2);
    fclose($file);

And it write's it like it should.

Upvotes: 0

Views: 547

Answers (2)

Shijin TR
Shijin TR

Reputation: 7788

Try like the following example

     <?php
          $list =array(
                       array('Comanda','Client','Categorie','Produs','UM','Cantitate','Actualizare'),
           array('P1','C1','CL1','2','2','Ct1','A1'),
           array('P2','C2','CL2','2','2','Ct2','A2'),
          );

       $fp = fopen('file.csv', 'w');

     foreach ($list as $fields) {
     fputcsv($fp, $fields);
    }

     fclose($fp)
   ?>

Upvotes: 1

Mr. Programmer
Mr. Programmer

Reputation: 3103

Try to add this line before the calling of fopen(): ini_set("auto_detect_line_endings", true)

Upvotes: 0

Related Questions