dongshi9719 2018-10-17 16:02
浏览 89
已采纳

在PHP中更改csv文件中的列标题名称和重新排序列

I have a CSV file and I want, via PHP, to change columns header names and reorder columns.

I tried this but this wont work for me:

function toCSV($data, $outstream) {
    if (count($data)) {
        // get header from keys
        fputcsv($outstream, array_keys($data[0]));
        // 
        foreach ($data as $row) {
            fputcsv($outstream, $row);
        }
    }
}
  • 写回答

2条回答 默认 最新

  • douyi1779 2018-10-18 12:23
    关注

    I found the some kind fo solution This will remove first row with columns names and put it in new csv file and add new columns names in the old one.

    $old_file = 'X.csv';
    $new_file = 'testdata_new.csv';
    
    $file_to_read = file_get_contents($old_file);  // Reading entire file
    $lines_to_read = explode("
    ", $file_to_read);  // Creating array of lines
    
    if ( $lines_to_read == '' ) die('EOF'); // No data 
    
    $line_to_append = array_shift( $lines_to_read ); // Extracting first line 
    
    $file_to_append = file_get_contents($new_file);  // Reading entire file
    
    if ( substr($file_to_append, -1, 1) != "
    " ) $file_to_append.="
    ";  // If new file doesn't ends in new line I add it
    
    // Writing files
    file_put_contents($new_file, $file_to_append . $line_to_append . "
    ");
    file_put_contents($old_file, implode("
    ", $lines_to_read));
    
    
    
      $header = "here write the names  
    ";
      $data = file_get_contents($old_file);
      file_put_contents($old_file, $header.$data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中
  • ¥15 请各位帮我看看是哪里出了问题