我有两个csv文件
file1的
苹果,芒果,香蕉
file2的
2,3,4,5
我希望输出文件为:
苹果,芒果,香蕉,2
苹果,芒果,香蕉,3
苹果,芒果,香蕉,4
Apple,Mango,Banana,5
如何使用PHP执行此操作?
<?php
$csv1 = file('Book2.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$csv2 = file('Book1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$output = fopen('output1.csv','w');
foreach ($csv1 as $value_csv1) {
foreach ($csv2 as $value_csv2) {
fwrite($output, $value_csv1 . ',' . $value_csv2 . PHP_EOL);
}
}
?>
答案 0 :(得分:0)
按部分读取文件比读取整个文件并将其存储在内存中要好得多。试试这个:
<?php
$file1 = fopen("Book1.csv", "r");
$file2 = fopen("Book2.csv", "r");
$output = fopen("output1.csv", "w");
$line2parts = array();
while (!feof($file1)) {
$line1 = "";
$line1 = fgets($file1);
$line1 = trim($line1);
if (empty($line1)) {
continue;
}
while (!feof($file2)) {
$line2 = "";
$line2 = fgets($file2);
$line2 = trim($line2);
if (empty($line2)) {
continue;
}
$line2parts = explode(",", $line2);
foreach ($line2parts as $line2part) {
/* if your writing a file that is intended for a
windows user you should append "\r\n" instead */
fwrite($output, $line1 . "," . $line2part . PHP_EOL);
}
}
}
fclose($file1);
fclose($file2);
fclose($output);
?>
希望这会有所帮助:)
答案 1 :(得分:0)
尝试使用fgetcsv()和file_get_contents();将输出分配给变量并写入文件。
<?php
$csv1 = file_get_contents('book1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);//apple, mango, banana
$row = 1;
if (($handle2 = fopen("book2.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle2, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $csv1.' '.$data[$c] . "<br />\n";
}
}
fclose($handle2);
}
?>
OUTPUT:
Apple, Mango, Banana ,2
Apple, Mango, Banana ,3
Apple, Mango, Banana ,4
Apple, Mango, Banana ,5
希望这会有所帮助: - )
答案 2 :(得分:0)
My previous example output is in the screen.
here's output to a file.
<?php
$output = fopen('output1.csv','w');
$csv1 = file_get_contents('book1.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);//apple, mango, banana
$row = 1;
if (($handle2 = fopen("book2.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle2, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$dataX = $csv1.' ,'.$data[$c];
fwrite($output, $dataX.PHP_EOL);
}
}
fclose($handle2);
}
?>