简体   繁体   中英

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.

  • Title line,
  • Line 1,
  • Line 2,
  • etc

But my csv shows like

  • Title line,
  • "Line1,Line2,etc"

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.

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)
   ?>

尝试在调用fopen()之前添加以下行:ini_set(“ auto_detect_line_endings”,true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM