PHP - 解析csv文件并将输出写入另一个csv文件

时间:2013-03-25 07:50:27

标签: php magento csv

我正在研究Magento产品的csv文件,我有一个包含3列的csv文件,如

<pre>Name, description, Color</pre>
<pre>t-shirt, tshirt description, "green, blue, yellow"</pre>

现在根据第3列(颜色)列的值,我想在单独的文件中输出每一行,并说&#34; new_products.csv&#34;以某种方式使得结果文件就像

<p>Name, description, Color</p>
<pre>t-shirt, tshirt description, green</pre>
<pre>t-shirt, tshirt description, blue</pre>
<pre>t-shirt, tshirt description, yellow</pre>

我已经开始使用此代码

$row = 1;

if (($handle = fopen("product.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
            $name = $data[0];
    $desc = $data[1];

    for ($c=0; $c < $num; $c++) {


        $fp = fopen('new_products.csv', 'w');

        if($c == 2){ //if we are at color field
            $color = explode(',', $data[$c]);
            $color_count = count($color);
            for($i=0; $i<$color_count; $i++){

                fputcsv($fp, array($name,$desc,$color[$i]));
            }

        }

    }
            $row++;
}
fclose($handle);
}

但是上面的代码只输出最后一行。

由于

1 个答案:

答案 0 :(得分:2)

最后,我能够找到解决方案。实际上,需要将文件指针设置在文件的末尾。

$row = 1;

if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    $name = $data[0];
    $desc = $data[1];


    for ($c=0; $c < $num; $c++) {            

        if($c == 2){ //if we are at color field
          $fp = fopen('file.csv', 'a'); //Open for writing only; place the file pointer at the end of the file.
            $color = explode(',', $data[$c]);
            $color_count = count($color);
            for($i=0; $i<$color_count; $i++){
                fputcsv($fp, array($name,$desc,$color[$i]));
            }
            fclose($fp);
        }

    }

            $row++;
}
fclose($handle);

}