How to write array values into a csv file in PHP?

孤街浪徒 提交于 2019-12-10 11:55:24

问题


I have an array whose structure is like $data = array{0=>'abc',1=>xyz,2=>tqs}

Now I need to write these values into a csv file. I need to display every value in 1st column and with everytime new row on new insert along with previous value already available.

Below is the code I am using but everytime I execute it I get the last value in the file:

for ($c=0; $c < $num; $c++) {
      echo $data[$c];
   echo  $query = "select prod_sku,prod_name 
    from
      tbl_product
    where 
     prod_sku = '".$data[$c]."'";
     $result = mysql_query($query);
     $row = mysql_fetch_array($result);
     if(empty($row)){
     print_r($row);
     echo 'test';
     $fp = fopen("file.csv", "w");
     print_r($data[0]);

      fputcsv($fp, $data[0]);
      fclose($fp);


  } 

How can i achieve this using PHP?


回答1:


The problem is that you are doing fopen inside the for loop, so every time the loop runs, your file gets re-written. Move the fopen and fclose outside of the loop and it will work. Like this;

$fp = fopen("file.csv", "w");
for ($c=0; $c < $num; $c++)
{
     $query = "select prod_sku,prod_name from tbl_product where prod_sku = '".$data[$c]."'";
     $result = mysql_query($query);
     $row = mysql_fetch_array($result);

     fputcsv($fp, $data);
} 
fclose($fp);



回答2:


If you use MySQL you could use SELECT ... INTO OUTFILE:

SELECT prod_sku, prod_name
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM tbl_product
WHERE 1

http://dev.mysql.com/doc/refman/5.0/en/select.html



来源:https://stackoverflow.com/questions/4290693/how-to-write-array-values-into-a-csv-file-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!