【问题标题】:Remove first line in CSV and then save the file overwriting existing删除 CSV 中的第一行,然后保存覆盖现有文件的文件
【发布时间】:2015-02-08 11:32:36
【问题描述】:

我有一个动态生成的 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 line7

输出文件为空。

艾玛

【问题讨论】:

    标签: php csv fgetcsv fputcsv


    【解决方案1】:

    您的代码中有一些错误。第一个是fgetcsv function 只得到一行,所以如果你想提取所有行,你需要一个循环。 fputcsv function 也是如此。

    另一个是 array_shift function 返回移位后的值,因此您将不需要的字符串分配给 $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);
    

    【讨论】:

    • 您在fputcsv($file,$data,",");的代码中有错误
    【解决方案2】:
    // 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-10
      • 2015-03-11
      • 2017-11-19
      • 2020-05-15
      • 2023-03-23
      • 2014-06-30
      • 2014-12-28
      • 1970-01-01
      相关资源
      最近更新 更多