Отредактируйте мой оригинальный пост. Я нашел ответ !!!! С помощью:)
Теперь у меня это работает, используя приведенный ниже код с благодарностью за совет по этому вопросу в комментариях:
<?php
$f = fopen('incident_csv\test.csv', 'w');
$query = "select column1, column2, column3
from table
where columns = values
";
$var1 = mysql_query($query, $database connection variable);
/* From Monkey Zeus */
$csv_lines = array();
// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){
$columns = array();
// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}
// Join on a comma
$csv_lines[] = implode(',', $columns);
}
// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
/* From Monkey Zeus */
fwrite($f, $csv_file_string);
?>
Вы можете сделать это:
$csv_lines = array();
// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){
$columns = array();
// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}
// Join on a comma
$csv_lines[] = implode(',', $columns);
// Write to the file right away. You are using PHP4 so I imagine system memory is not plentiful
// If you use this then there is no need for the "$csv_lines[] =" from above
// nor the $csv_file_string after the while loop
// fwrite($f, implode(',', $columns)."\n");
}
// fclose($f); // If you choose to write to the file during the while loop then close the file handle when you are finished
// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
Вы можете просто воспользоваться функцией arrayToCsv:
function arrayToCsv($array) {
$string = array();
foreach ($array as $field) {
$string[] = implode(';', $field);
}
return implode("\n", $string);
}
$a = array(
array('First Field of First Line', 'Second Field of First Line'),
array('First Field of Second Line', 'Second Field of Second Line')
);
fwrite($f, arrayToCsv($a));
Но не забудьте иметь свой $f
установлено с $f = fopen('file location', 'w');
Надеюсь, я был полезным.