删除CSV中的第一行,然后保存覆盖现有文件的文件


Remove first line in CSV and then save the file overwriting existing

我有一个动态生成的CSV文件。我想删除 CSV 的第一行,然后再次保存。

我已经用谷歌搜索并能够获得第一行 csv,但删除后再次编写的部分是我卡住的地方。

这是示例

line1,data1
line2,data2
line3,data3

我想要实现的目标

line2,data2
line3,data3

删除第一行并再次保存文件

这是我的代码

$file = fopen('words.csv', 'r');
$data = fgetcsv($file,10000,",");
$data = array_shift($data);
$file = fopen('words.csv', 'w');
fputcsv($file,$data,",");
fclose($file);

我明白这个: ! ) Warning: fputcsv() expects parameter 2 to be array, string given in C:'wamp'www'scrape'test.php on line 7

并且输出文件为空。

艾哈迈尔

// Read the file
$file = fopen('words.csv', 'r');
// Iterate over it to get every line 
while (($line = fgetcsv($file)) !== FALSE) {
  // Store every line in an array
  $data[] = $line;
}
fclose($file);
// Remove the first element from the stored array / first line of file being read
array_shift($data);
// Open file for writing
$file = fopen('words.csv', 'w');
// Write remaining lines to file
foreach ($data as $fields) {
    fputcsv($file, $fields);
}
fclose($file);

你的代码中有一些错误。第一个是 fgetcsv 函数只获取一行,所以如果你想提取所有行,你需要一个循环。fputcsv 函数也会发生同样的情况。

另一个是array_shift函数返回移位值,因此您将分配给$data不需要的字符串。

所以,我认为你的代码必须是这样的:

$file = fopen('words.csv', 'r');
$data=array();
while (($data_tmp = fgetcsv($file, 1000, ",")) !== FALSE) {
       $data[] = $data_tmp;
}
fclose($file);
array_shift($data);
$file = fopen('words.csv', 'w');
foreach($data as $d){
    fputcsv($file,$d);
}
fclose($file);