Php SYMFONY2:StreamedResponse不工作的csv导出
我有一个问题,我的代码看起来不错,我有一个状态200,正确的标题,但我的csv文件创建将不会关闭 我没有错,所以我不明白为什么 如果你能帮助我 多谢各位 这是我的密码:Php SYMFONY2:StreamedResponse不工作的csv导出,php,symfony,csv,doctrine-orm,Php,Symfony,Csv,Doctrine Orm,我有一个问题,我的代码看起来不错,我有一个状态200,正确的标题,但我的csv文件创建将不会关闭 我没有错,所以我不明白为什么 如果你能帮助我 多谢各位 这是我的密码: namespace Rac\CaraBundle\Manager; /* Imports */ use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\Validator\ValidatorInterface; use Sy
namespace Rac\CaraBundle\Manager;
/* Imports */
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\ValidatorInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\StreamedResponse;
/* Local Imports */
use Rac\CaraBundle\Entity\Contact;
/**
* Class CSV Contact Importer
*
*/
class CSVContactImporterManager {
/**
* @var ObjectManager
*/
private $om;
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* @var ValidatorInterface
*/
private $validator;
/**
* @var ContactManager
*/
private $contactManager;
/**
* @param EventDispatcherInterface $eventDispatcher
* @param ObjectManager $om
* @param Contact $contactManager
*
*/
public function __construct(
EventDispatcherInterface $eventDispatcher, ObjectManager $om, ValidatorInterface $validator, ContactManager $contactManager
) {
$this->eventDispatcher = $eventDispatcher;
$this->om = $om;
$this->validator = $validator;
$this->contactManager = $contactManager;
}
public function getExportToCSVResponse() {
// get the service container to pass to the closure
$contactList = $this->contactManager->findAll();
$response = new StreamedResponse();
$response->setCallback(
function () use ($contactList) {
//Import all contacts
$handle = fopen('php://output', 'r+');
// Add a row with the names of the columns for the CSV file
fputcsv($handle, array('Nom', 'Prénom', 'Société', 'Position', 'Email', 'Adresse', 'Téléphone', 'Téléphone mobile'), "\t");
$header = array();
//print_r($contactList);
foreach ($contactList as $row) {
fputcsv($handle, array(
$row->getFirstName(),
$row->getLastName(),
$row->getCompany(),
$row->getPosition(),
$row->getEmail(),
$row->getAddress(),
$row->getPhone(),
$row->getMobile(),
), "\t");
}
fclose($handle);
}
);
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;
}
和我的控制器:
use Rac\CaraBundle\Entity\Contact;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use UCS\Bundle\RichUIBundle\Controller\BaseController;
use UCS\Bundle\RichUIBundle\Serializer\AbstractListSerializer;
/**
* Contact BackOffice Environment Controller.
*
*
*
* @Route("/contact_environment")
*/
class ContactEnvironmentController extends BaseController{
/* My code here..*/
/**
* @Route("/export", name="contact_environment_export",options={"expose"=true})
* @Method("GET")
*
* @return type
*/
public function exort(){
$manager = $this->get("cara.csv_contact_importer_manager");
return $manager->getExportToCSVResponse();
}
}
我的标题:
Cache-Control:no-cache, private
Connection:close
Content-Disposition:attachment; filename="export.csv"
Content-Type:application/force-download
根据作者的要求,这里是一个基于响应的解决方案。在这种设计中,csv服务只返回csv文本。响应在控制器中生成 csv生成器:
class ScheduleGameUtilDumpCSV
{
public function getFileExtension() { return 'csv'; }
public function getContentType() { return 'text/csv'; }
public function dump($games)
{
$fp = fopen('php://temp','r+');
// Header
$row = array(
"Game","Date","DOW","Time","Venue","Field",
"Group","HT Slot","AT Slot",
"Home Team Name",'Away Team Name',
);
fputcsv($fp,$row);
// Games is passed in
foreach($games as $game)
{
// Date/Time
$dt = $game->getDtBeg();
$dow = $dt->format('D');
$date = $dt->format('m/d/Y');
$time = $dt->format('g:i A');
// Build up row
$row = array();
$row[] = $game->getNum();
$row[] = $date;
$row[] = $dow;
$row[] = $time;
$row[] = $game->getVenueName();
$row[] = $game->getFieldName();
$row[] = $game->getGroupKey();
$row[] = $game->getHomeTeam()->getGroupSlot();
$row[] = $game->getAwayTeam()->getGroupSlot();
$row[] = $game->getHomeTeam()->getName();
$row[] = $game->getAwayTeam()->getName();
fputcsv($fp,$row);
}
// Return the content
rewind($fp);
$csv = stream_get_contents($fp);
fclose($fp);
return $csv;
}
控制员:
public function renderResponse(Request $request)
{
// Model is passed via request
$model = $request->attributes->get('model');
$games = $model->loadGames();
// The csv service
$dumper = $this->get('csv_dumper_service');
// Response with content
$response = new Response($dumper->dump($games);
// file prefix was injected
$outFileName = $this->prefix . date('Ymd-Hi') . '.' . $dumper->getFileExtension();
$response->headers->set('Content-Type', $dumper->getContentType());
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"',$outFileName));
return $response;
}
下面是一个工作正常的流式Symfony响应。该类创建一个要下载的文件,其中包含导出的数据
class ExportManagerService {
protected $filename;
protected $repdata;
public function publishToCSVReportData(){
$repdata = $this->repdata;
// array check
if (is_array($repdata)){
$response = new StreamedResponse();
$response->setCallback(
function () use ($repdata) {
$handle = fopen('php://output', 'r+');
foreach ($repdata as $row) {
$values = $row['values'];
$position = $row['position'];
$fileData = $this->structureDataInFile($values, $position);
fputcsv($handle, $fileData);
}
fclose($handle);
}
);
} else{
throw new Exception('The report data to be exported should be an array!');
}
$compstring = substr($this->filename,-4);
if($compstring === '.csv'){
// csv file type check
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', 'attachment; filename='.$this->filename);
} else { throw new Exception('Incorrect file name!');}
return $response;
}
public function structureDataInFile(array $values, $position){
switch ($position){
case 'TopMain':
for ($i = 0; $i < 4; $i++){
array_unshift($values, ' ');
}
return $values;
break;
case 'Top':
$space = array(' ', ' ', ' ');
array_splice($values,1,0,$space);
return $values;
break;
case 'TopFirst':
for ($i = 0; $i < 1; $i++){
array_unshift($values, ' ');
}
$space = array(' ', ' ');
array_splice($values,2,0,$space);
return $values;
break;
case 'TopSecond':
for ($i = 0; $i < 2; $i++){
array_unshift($values, ' ');
}
$space = array(' ');
array_splice($values,3,0,$space);
return $values;
break;
case 'TopThird':
for ($i = 0; $i < 3; $i++){
array_unshift($values, ' ');
}
return $values;
break;
default:
return $values;
}
}
/*
* @var array
*/
public function setRepdata($repdata){
$this->repdata = $repdata;
}
/*
* @var string
*/
public function setFilename($filename){
$this->filename = $filename;
}
}
类ExportManagerService{
受保护的$filename;
受保护的数据;
公共函数publishToCSVReportData(){
$repdata=$this->repdata;
//数组检查
if(is_数组($repdata)){
$response=新的流响应();
$response->setCallback(
函数()使用($repdata){
$handle=fopen($handle)php://output","r+";;
foreach($repdata作为$row){
$values=$row['values'];
$position=$row['position'];
$fileData=$this->structuredatainfle($values,$position);
fputcsv($handle,$fileData);
}
fclose($handle);
}
);
}否则{
抛出新异常('要导出的报表数据应该是数组!');
}
$compstring=substr($this->filename,-4);
如果($compstring=='.csv'){
//csv文件类型检查
$response->headers->set('Content-Type','application/force-download');
$response->headers->set('Content-Disposition','attachment;filename='。$this->filename);
}else{抛出新异常('error file name!');}
返回$response;
}
公共函数structuredatainfle(数组$values,$position){
开关($位置){
案例“TopMain”:
对于($i=0;$i<4;$i++){
数组_unshift($value,”);
}
返回$value;
打破
案例“顶部”:
$space=数组(“”,“”,“”);
阵列拼接($value,1,0,$space);
返回$value;
打破
案例“TopFirst”:
对于($i=0;$i<1;$i++){
数组_unshift($value,”);
}
$space=数组(“”,”);
阵列拼接($value,2,0,$space);
返回$value;
打破
“上秒”情况:
对于($i=0;$i<2;$i++){
数组_unshift($value,”);
}
$space=数组(“”);
阵列拼接($value,3,0,$space);
返回$value;
打破
“前三名”案例:
对于($i=0;$i<3;$i++){
数组_unshift($value,”);
}
返回$value;
打破
违约:
返回$value;
}
}
/*
*@var数组
*/
公共函数setRepdata($repdata){
$this->repdata=$repdata;
}
/*
*@var字符串
*/
公共函数setFilename($filename){
$this->filename=$filename;
}
}
这里有一个更简短的方法:)
为什么在命名动作时省略了“动作”后缀?您的函数是否应命名为“exportAction()”?我修改为测试,但不幸的是,它没有更改。请尝试添加
flush()
,如前所述,它不起作用。请尝试将内容类型设置为“text/csv”。虽然前面的答案可能更简单,但我发现这是使用streamdResponse的一个很好的示例。我很惊讶我们需要明确地写信给php://output(我本以为在这种情况下这是自动的)。我相信现在推荐的设置处置方式是$response->headers->makeDisposition(ResponseHeaderBag::disposition\u ATTACHMENT,$this->filename)代码>。。。这有什么不同吗?
/**
* Class CsvResponse
*/
class CsvResponse extends StreamedResponse
{
/**
* CsvResponse constructor.
*
* @param array $rows
* @param string $fileName
*/
public function __construct(array $rows, $fileName)
{
parent::__construct(
function () use ($rows) {
$this->convertArrayToCsv($rows);
},
self::HTTP_OK,
[
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Type' => 'text/csv',
]
);
}
/**
* @param array $rows
*
*/
private function convertArrayToCsv(array $rows)
{
$tempFile = fopen('php://output', 'r+b');
foreach ($rows as $row) {
fputcsv($tempFile, $row);
}
fclose($tempFile);
}
}