开发者

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

开发者 https://www.devze.com 2023-01-27 17:33 出处:网络
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 everytim

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开发者_StackOverflow");
     print_r($data[0]);

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


  } 

How can i achieve this using PHP?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消