I'm having two CSV files. The first one contains two columns (comma separated) the second one contains just one column.
I'm trying to combine them and move the column from the second file as a last column to the first file.
The problem: when I run the script the column goes to the first file but instead of append as last column it completely replace the content of the file.
file_1.csv
1,13414214
6,13414214
13,13
3,33129
file_2.csv
title_1
title_2
title_3
title_4
When combined the file_1.csv should looks like
1,13414214,title_1
6,13414214,title_2
13,13,title_3
3,33129,title_4
The files are with same line numbers.
This is what I have so far
$file = fopen("file_1.csv","w");
$row = 1;
if (($handle = fopen("file_2.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
$num = count($data);
$row++;
echo $data[0]. "\n";
fputcsv($file, $data);
}
}
fclose($handle);
fclose($file);
Any help is appreciated.
UPDATE: This is the output from the answer
1,13414214
,title_1
6,13414214
,title_2
13,13
,title_3
3,33129
,title_4
For simplicity I would not try to attempt to write to
file_1. Just read fromfile_1andfile_2and then write tofile_3. Something like:As you can see, I treat the files as simple text file, not as CVS file, because I don't need to do anything with the data in them.
Note that this will only work somewhat when
file_1.csvandfile_2.csvcontain the same number of lines.Oh, and also: This might not be the best approach for very large files. Then it would probably be better, albeit a lot slower, to read them line by line.