Экспортируйте массив в .csv используя

У меня проблема с моим .csv. Поэтому я попытался сгенерировать .csv из массива с помощью php. По мнению у меня есть:

<form id="form_logistique" action="myroute" method="post">
<div class="form-group " style="float: left;">
<label class="control-label" for="" style="display: inline-block; padding-right: 20px;">Date min</label>
<input type="text" id="date_min" name="date_min.name" value="date_min" placeholder="Date min" class="form-control datepicker"  />
</div>

<div class="form-group" style="float: left;padding-left: 20px;">
<label class="control-label" for="" style="display: inline-block; padding-right: 20px;">Date max</label>
<input type="text" id="date_max" name="date_max" value="{{ date_max" placeholder="Date max" class="form-control datepicker"  />
</div>


<input type="submit" class="btn btn-primary" style="margin-top: 25px;margin-left: 20px;" value="Rechercher"></input>
<input type="submit" class="btn btn-succes" style="margin-top: 25px;margin-left: 20px;" name="export" value="Exporter"></input>
</form>

В php:

 public function getLogistique()
{
$this->form_logistique = new Form\Form(
new Form\Field\Text('date_min', '', true),
new Form\Field\Text('date_max','',true),
);
$date_min = '';
$date_max = '';
if ($this->getRequest()->isPostMethod() && $this->form_logistique->bind($_POST)){
$date_min = $this->form_logistique->date_min->getValue();
$date_max = $this->form_logistique->date_max->getValue();
}
$interdit  = array(";", ",", ":", "*", "/", "|", "?", '"', "<", ">", "!", "_", "@", "[", "]", "\\", "{", "}", "~");
$aGifts = Gain::getGiftForLogistique($date_min, $date_max, $statut);
foreach($aGifts as $gift){
$date = explode(' ', $gift['date_gain']);
$gift['ref_article']        = $gift['ref_article'];
$gift['nom']                = str_replace($interdit,"",$gift['nom']);
$gift['prenom']             = str_replace($interdit,"",$gift['prenom']);
$gift['pseudo']             = $gift['pseudo'];
$gift['numero']             = trim(str_replace(";",",",str_replace("\\"," ",$gift['numero'])));
$gift['rue']                = str_replace($interdit,"",$gift['rue']);
$gift['complement']         = str_replace($interdit,"",$gift['complement']);
$gift['code_postal']        = $gift['code_postal'];
$gift['ville']              = str_replace(";",",",str_replace("\\"," ",$gift['ville']));
$gift['pays']               = $gift['pays'];
$gift['email']              = Gain::getEmailByIdm($gift['pseudo']);
$gift['tel']                = str_replace(";",",",str_replace("\\"," ",$gift['tel']));
$gift['id_instant_gagnant'] = $gift['id_instant_gagnant'];
$gift['date_gain']          = $date[0];
$aFilterGifts[] = $gift;
}
$this->aFilterGifts = $aFilterGifts;
if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array(''Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
}
return $this->render('template/customer_service/member/logistique.twig');
}

.Csv генерируется, но проблема в том, что после массива в .csv у меня есть все содержимое .html страницы, и я не понимаю, в чем проблема. Пожалуйста, помогите мне! Спасибо заранее

0

Решение

Проблема заключается в следующем:

if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array('Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
}
return $this->render('template/customer_service/member/logistique.twig');

Функция записывает заголовки и содержимое файла CSV в STDOUT (php://output), но затем весь цирк продолжается. Эта функция возвращает содержимое шаблона его родительской функции, и это, вероятно, также переводит его в STDOUT (используя echo, print или что-то другое). Легче всего сделать здесь (но не правильно) поставить die(); после fclose($output);:

if (isset($_POST['export'])) {
$output = fopen('php://output', 'w');
$sFileName = 'Fichier_de_logistique.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header('Content-Type: application/download');
fwrite($output, "sep=;\n");
fputcsv($output, array('Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
die();
}
return $this->render('template/customer_service/member/logistique.twig');

На мой взгляд, правильный путь — создать новый маршрут и действие контроллера для экспорта в CSV без вывода HTML.

2

Другие решения

Ваш вопрос не очень понятен, но, возможно, вы захотите прекратить выполнение скрипта после fclose ().

0

это потому, что в какой-то момент в коде у вас может быть эхо или что-то напечатать. Лучшим подходом было бы записать CSV в файл. А затем отправьте этот файл как Content-Disposition: attachment. Как в приведенном ниже коде, где файл является путем к файлу.

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
0

fputcsv ($ output, array (» Nom ‘,’ Prenom ‘), «;»);

опечатка здесь — двойная одинарная кавычка перед ном.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector