用php更新csv中的一列记录


update one column record in a csv with php

我的csv文件中有两列,例如:

    image    gallery
    /1.jpg   /a.jpg;/b.jpg
   .....      .....

现在我想将库内容更新为/1.jpg;/a.jpg;/b.jpg。即将图像collomn和;的内容添加到图库内容中。

以下是我的代码。当我运行它时。它无法更新csv的内容。我被卡住了。

$dir   = getcwd();
$files = scandir($dir);
foreach ($files as $file) {
$parts = pathinfo($file);
if ($parts['extension']!="csv") {
    continue;
}
if (($handle = fopen($file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
        $data[1]=$data[0].";".$data[1];
        fputcsv($file, $data);
    }
    fclose($handle);
}

以写入或追加模式打开文件fputcsv期望第一个参数是resource,并且您已经给出了文件路径这导致了问题改变它fputcsv($handle, $data);

请先检查文件权限,然后必须将句柄更改为读写,还请检查数据[1]是否具有值。因为在您的代码中,data[0]只会将行提取为用";"分隔的字符串,所以您必须分解它,然后再进行操作。