问题
I'm trying to attach an Excel file in a SwiftMailer message.
The trick is that I don't want to save the excel file and then attach it and then delete it, instead I just want to generate the excel and attach that to the message.
This function allows to attach a OutputByteStream
/**
* Create a new Attachment.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Mime_Attachment
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
There is a function in Symfony PHPExcel bundle to create the response
/**
* Stream the file as Response.
*
* @param \PHPExcel_Writer_IWriter $writer
* @param int $status
* @param array $headers
*
* @return StreamedResponse
*/
public function createStreamedResponse(\PHPExcel_Writer_IWriter $writer, $status = 200, $headers = array())
{
return new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
},
$status,
$headers
);
}
They seems to call to that callback when they are rendering the reponse, but How can I save the php://output in a variable or something to pass it to newInstance method?
I tried passing the response object (StreamedResponse) but it only have the headers, I also tried with $response->getContent() and passing $writer->save('php://output') to newInstance method.
回答1:
use stream_get_contents
$attachment = \Swift_Attachment::newInstance(stream_get_contents(createStreamedResponse(...)), 'test.xls', 'application/vnd.ms-excel');
(dont know hat your actual mimetype is)
回答2:
I made the trick like this :
Firstly, I use the output buffering and retrieve the content of the output buffer :
ob_start();
$writer = new Xlsx($excelFile);
$writer->save('php://output');
$data = ob_get_contents();
ob_end_clean();
Then I retrieve the $attachement :
$attachment = \Swift_Attachment::newInstance($data, $fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
Finally I attach the file to the mail like in the SwiftMailer documentation :
$email->attach($attachment);
回答3:
With the new Symfony Mailer component you can do that :
//same as @tCot response
ob_start();
$writer = new Xlsx($excelFile);
$writer->save('php://output');
$data = ob_get_contents();
ob_end_clean();
And in your email declaration :
$email->embed($data, $filename) //The third parameters (mime type) can be guess by Symfony
来源:https://stackoverflow.com/questions/43833370/attach-excel-stream-to-swiftmailer-message