PHP Как конвертировать массив в CSV с помощью функции fputcsv
Пожалуйста, у меня есть следующий массив:
array(3) {
[0]=>
array(2) {
[0]=>
string(6) "lkjhgj"
[1]=>
string(16) "jhgjhg@jhgjj.com"
}
[1]=>
array(2) {
[0]=>
string(5) "hgjk,"
[1]=>
string(18) "kjhgfghj@dgdfg.com"
}
[2]=>
array(2) {
[0]=>
string(9) "dddd ffff"
[1]=>
string(13) "dddd@gmail.fr"
}
}
Я хочу поместить его в CSV-файл, поэтому я попытался:
$fichier = 'file.csv';
$fp = fopen($fichier, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$fichier);
Но когда я скачал файл, я обнаружил, что он пуст!
Пожалуйста, освоите любую идею? заранее спасибо
PS: разрешения 777
3 ответа
Решение
$fichier = 'file.csv';
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$fichier\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
exit();
Если вы сохраняете массив в сессии и вопросы закодированных символов.
session_start();
$fp = fopen($_SESSION['CSV']['type'].'.csv', 'w');
foreach ($_SESSION['CSV'] as $fields) {
$val1 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[0], ENT_QUOTES | ENT_XML1, 'UTF-8')));
$val2 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[1], ENT_QUOTES | ENT_XML1, 'UTF-8')));
$val3 = htmlspecialchars_decode(utf8_decode(html_entity_decode($fields[2], ENT_QUOTES | ENT_XML1, 'UTF-8')));
fputcsv($fp, array($val1,$val2,$val3,$val4,$val5));
}
fclose($fp);
если кто-то хочет экспортировать результаты запроса с динамическими заголовками в массив, а затем в файл csv, вы можете использовать следующую функцию:
function exportCSVFile($fieldsNames, $result)
{
$fileName = "result.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$fileName");
header("Pragma: no-cache");
header("Expires: 0");
$stdout = fopen('php://output', 'w');
fputcsv($stdout, $fieldsNames, ',', '"'); // put the headers or fields Names
$resultArray = array();
$tempRowHolder = array();
/*
build the finalized array which will be used to export the result as csv
*/
for ($i = 0; $i < count($result); $i++) {
for ($j = 0; $j < count($fieldsNames); $j++) {
$tempRowHolder[$j] = $result[$i][$fieldsNames[$j]]; // fetch a row by the different fields names
}
/* push the row from the tempRowHolder array to the main array($resultArray) */
array_push($resultArray, $tempRowHolder);
/* clear the temporary array (the holder of the row) to use it fresh in the next iteration */
$tempRowHolder = [];
}
$i = 0;
/* put the finalized array into the csv file */
while ($i < count($resultArray)) {
fputcsv($stdout, $resultArray[$i++]);
}
fclose($stdout);
}