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

在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);
        }
    }
}

图片转代码服务由CSDN问答提供 功能建议

我有一个CSV文件,我希望通过PHP更改列标题名称并重新排序列。

我尝试了这个,但这对我不起作用:

  function toCSV($ data,$ outstream){
 if(count($ data)  )){
 //从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);
    
    已采纳该答案
    打赏 评论
  • dongyue9864 2018-10-17 16:47

    Kindly try this.

    $inputCsv = 'sample.csv';
    $outputCsv = 'output.csv';
    
    $inputHandle = fopen($inputCsv, 'r');
    $header = fgetcsv($inputHandle);
    
    
    /*
     * 1. For name change
     */
    $header[0] = 'column 1 name changed here';
    $header[2] = 'column 3 name changed here';
    
     /*
         * 2. For header order change I am shuffling column names
     */
    shuffle($header);
    
     $outputHandle = fopen($outputCsv, 'w');
     fputcsv($outputHandle, $header);
    
    
    while($row = fgetcsv($inputHandle)){
        fputcsv($outputHandle, $row);
    }
    
    fclose($outputHandle);
    
    打赏 评论

相关推荐 更多相似问题