php - 如何通过行号从 CSV 文件中删除特定行?

标签 php csv

我试图通过行号从 CSV 文件中删除一行,我在 URL 中将其作为参数获取。

我在这里看到了一些讨论,但主要是“通过存储在第一列的 id 删除一行”等等。我试图以与这些讨论中的其他人相同的方式来制作它,但它不起作用。我只是改变了条件。

if (isset($_GET['remove']))
{
    $RowNo = $_GET['remove'];   //getting row number
    $row = 1;
    if (($handle = fopen($FileName, "w+")) !== FALSE)
    {
        while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
        {
//Here, I don't understand, why this condition does not work.
            if ($row != $RowNo)
            {
                fputcsv($handle, $data, ';');
            }
            $row++;
        }
        fclose($handle);
    }
}

我想,它也应该对我有用,BCS 只是条件改变了。但事实并非如此。它清除整个文件。你能帮我解决一下吗?

非常感谢您的任何建议。丹尼尔。

最佳答案

您可以使用 file() 将文件加载为行数组.

然后删除该行并将文件写回。

// read the file into an array    
$fileAsArray = file($FileName);

// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $_GET['remove'] - 1;

// check if the line to delete is greater than the length of the file
if ($lineToDelete > sizeof($fileAsArray)) {
    throw new Exception("Given line number was not found in file.");
}

//remove the line
unset($fileAsArray[$lineToDelete]);

// open the file for reading
if (!is_writable($fileName) || !$fp = fopen($fileName, 'w+')) {
    // print an error
    throw new Exception("Cannot open file ($fileName)");
}

// if $fp is valid
if ($fp) {
    // write the array to the file
    foreach ($fileAsArray as $line) {
        fwrite($fp, $line);
    }

    // close the file
    fclose($fp);
}

如果你有一个 unix 系统,你也可以使用 sed 命令:

exec("sed -e '{$lineToDelete}d' {$FileName}");

如果使用了用户输入,请记住清理命令参数: https://www.php.net/manual/de/function.escapeshellcmd.php

关于php - 如何通过行号从 CSV 文件中删除特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58181289/

相关文章:

python - Pandas Left Merge 与 xlsx 和 CSV 在输出中生成空值列

php - mysql加入: get all rows that matches the rows that matches notification type is zero

php - PHP 是否具有与 Java 'synchronized' 等效的功能,或者这不是必需的?

php - 对于每个类别行产品

php - 防止脚本在页面刷新时重新执行操作

php - XDebug 无法连接到客户端

python - 如何将 Numpy 4D 数组保存为 CSV?

javascript - 从 csv 制作二维数组

c++ - 高效读取csv文件的最后一行

java - OpenCSV 扁平化到层次结构数据解析