Search code examples
phpcsvfputcsv

How save all the results of a php query to a .txt file?


My query gives me a result in an array :

$donnnes =

Table ( [0] => Table ( [sku_code] => A1101_0090_TU [SKU_EAN] => 9346799868270 ) ) 

My .txt file create itself well but fills up like this :

MMXC1_|9346799868270|0|0

MMXC1_| |0|1

MMXC1_| |1|4

...

Only the first line is completely filled, in the others there is nothing between the two pipes '|' after "MMXC1_" while in my var_dump($data_final); all the data is there, where does my error come from?

$resultat = mysqli_query($bdd, "SELECT trim(concat(concat(SKU_ITEM_VARIANT,'_'),trim(SKU_SIZE)))as sku_code , SKU_EAN  FROM dwh_dev.dwh_d_sku"); 

    while ($donnees[] = mysqli_fetch_assoc($resultat)) {

    }
  print_r($donnees); //Array ( [0] => Array ( [sku_code] => A1101_0090_TU [SKU_EAN] => 9346799868270 ) 

    $constante = "MMXC1_";    

    $temp2 = array_column($donnees,  'SKU_EAN', 'sku_code');


            if (($handle = fopen("$nomcsv", "r")) !== FALSE) { 

                $firstLine = true;

                while (($data = fgetcsv($handle, 1000000, ";")) !== FALSE) 
                {   
                    if(!$firstLine) {


                        $SKU_EAN = $temp2[$data[6].'_'.$data[7].'_'.$data[8]];
                        var_dump($SKU_EAN); //A1101_0090_TU A1104_0090_TU

                        // Create line here and immediately add it to `$data_final`
                        $data_final[] = $constante.'|'.$SKU_EAN.'|'.$data[12].'|'.$data[13]; 
                        var_dump($data_final); // array(1) { ["A1101_0090_TU"]=> string(13) "9346799868270" } array(1) { [0]=> string(26) "MMXC1_|9346799868270|0|0" } array(2) { [0]=> string(26) "MMXC1_|9346799868270|0|0" [1]=> string(13) "MMXC1_||0|0" }
                     }
                     $firstLine = false;
                }   
            }



                     $cheminfile = "//alcyons/IT/PhotoShoot/retail/CSV/TXT_Finaux/MMX".date('His').".txt";

                    $fp = fopen("$cheminfile", "w");

                    fputcsv($fp, $data_final,  "\n");                              

                    fclose($fp);    

Solution

  • Why are you using fputcsv on a .txt file? use fwrite instead.

    replace

    fputcsv($fp, $data_final,  "\n");                              
    

    with

    foreach($data_final as $data){
       fwrite($fp,$data."\n");
    }