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


PHP - parse a csv file and write output to another csv file

我正在制作Magento产品csv文件,我有一个csv文件,有3列,如

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

现在根据列3列(颜色)的值,我想在一个单独的文件中输出每一行,比如"new_products.csv",这样得到的文件就像

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

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

谢谢

我终于能够自己找到解决方案了。实际上需要在文件末尾设置文件指针。

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

}