我有一个CSV文件,我想通过PHP更改列标题名称并重新排序列。
我尝试过,但这对我不起作用:
function toCSV($data, $outstream) {
if (count($data)) {
// get header from keys
fputcsv($outstream, array_keys($data[0]));
//
foreach ($data as $row) {
fputcsv($outstream, $row);
}
}
}
答案 0 :(得分:0)
请尝试一下。
$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);
答案 1 :(得分:0)
我找到了某种解决方案 这将删除具有列名的第一行,并将其放入新的csv文件中,并在旧的csv文件中添加新的列名。
$old_file = 'X.csv';
$new_file = 'testdata_new.csv';
$file_to_read = file_get_contents($old_file); // Reading entire file
$lines_to_read = explode("\n", $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) != "\n" ) $file_to_append.="\n"; // 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 . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));
$header = "here write the names \r\n";
$data = file_get_contents($old_file);
file_put_contents($old_file, $header.$data);