使用php将多个嵌套数组写入文件
问题描述:
What I am trying to do is grab a Business Catalyst-generated CSV of my products. But it always includes a whole lot of stuff I don't need.
I have a script that uses fgetcsv(). The code is
<?php
$file_handle = fopen("ProductExport2.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1000000);
$tableDisplay = "<tr><td>" . $line_of_text[0] . "</td><td>" . $line_of_text[1] . "</td><td>" . $line_of_text[2] . "</td><td>" . $line_of_text[4] . "</td><td>" . $line_of_text[6] . "</td><td>" . $line_of_text[49] . "</td></tr>";
echo $tableDisplay;
}
fclose($file_handle);
?>
All this does is display the data I want.
However, what I want to do now is write a new CSV file out of this. Using fwrite() only results in writing just the first entry of the data.
Any ideas?
答
Something like this.
<?php
$file_handle = fopen("ProductExport2.csv", "r");
$data = '';
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1000000);
$data .= $line_of_text[0] . "," . $line_of_text[1] . "," . $line_of_text[2] . "," . $line_of_text[4] . "," . $line_of_text[6] . "," . $line_of_text[49] . "
";
}
fclose($file_handle);
$new_file_handle = fopen("ProductExport2_reduced.csv", "w");
fwrite($new_file_handle, $data);
?>
答
It's very similar to the code you already have:
<?php
$file_handle = fopen("ProductExport2.csv", "w");
// Iterate through the data entries
foreach($my_data as $entry) {
// Write the "columns" of each entry as a comma-separated string to the file
fputcsv($file_handle, $entry);
}
fclose($file_handle);
$my_data
has to be a two-dimensional array.
If you want to read your existing file, process its contents and write it to a different file, do it like this:
<?php
$file_handle = fopen("ProductExport2.csv", "r");
$file_handle_output = fopen("ProductExport2_new.csv", "w");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1000000);
// Change $line_of_text elements here
// for example $line_of_text[1] += 100;
// ...
fputcsv($file_handle_output, $line_of_text);
}
fclose($file_handle);
fclose($file_handle_output);
?>