如何在PHP中将数组值写入csv文件? [英] How to write array values into a csv file in PHP?
问题描述
我有一个数组,其结构类似于 $ data = array {0 =>'abc',1 => xyz,2 => tqs}
/ p>
现在我需要将这些值写入一个csv文件。我需要在第一列显示每一个值,每次在新插入的新行以及之前的值已经可用。
下面是我使用的代码,但每次执行我得到了文件中的最后一个值:
$ p $ 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);
$ b $ p $如何使用PHP实现这个功能?
问题在于你在for循环中执行 fopen
,所以每次循环运行时,文件都会被重写。在循环外面移动 fopen
和 fclose
,它将会起作用。像这样;
$ 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);
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?
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);
这篇关于如何在PHP中将数组值写入csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!