why csv export not working? - symfony

I try to do a csv export on my symfony project and i think that something is wrong because the function return a simple response and don't download the csv.
here is the function:
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);
return $response;
}

After creating a streamed response object, you needed to add the callback function that will fill out your response object with content: $response->setCallback().
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$response->setCallback(function() {
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name', 'Adress', 'City', 'Code'),';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment;
filename='.$fileName);
return $response;
}

Related

How to export image in excel file from mysql database dynamically

I want to export image from mysql database into an excel file using phpexcel.I have done it with static value but can not do it dynamically.
<?php
include ('config.php');
function my_constants(){
$url = 'http://' . $_SERVER['HTTP_HOST'] . "/phpexcel_gd/";
$path = $_SERVER['DOCUMENT_ROOT'] . '/phpexcel_gd/';
define('SITEURL', $url);
define('SITEPATH', str_replace('\\', '/', $path));
}
function report_details($display = null) {
if($display){
$imagePath = SITEURL . "images/";
} else {
$imagePath = SITEPATH . "images/";
}
// $select_query = mysqli_query($conn,"SELECT orderid, image_name,image_path FROM tbl_order_details WHERE orderid = '240419-0001-A1-B1'");
// $select_query_row = mysqli_fetch_array($select_query);
// $orderid = $select_query['orderid'];
// $image_name= $select_query['image_name'];
// $image_path = $select_query['image_path'];
$reportdetails = array(
// array('Image' => $image_path . $image_name,'orderid' => $orderid),
array('BrandIcon' => $imagePath . "github.png",'Comapany' => "Github",'Rank' => "3",'Link' => "https://github.com/"),
array('BrandIcon' => $imagePath . "bootstrap.png",'Comapany' => "Bootstrap",'Rank' => "4",'Link' => "http://getbootstrap.com/"),
array('BrandIcon' => $imagePath . "so-icon.png",'Comapany' => "Stack Overflow",'Rank' => "3",'Link' => "http://stackoverflow.com/"),
);
return $reportdetails;
}
/**
* Create excel by from ajax request
*/
function xlscreation_ajax() {
$reportdetails = report_details();
require_once SITEPATH . 'PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'BrandIcon',
'B' => 'Company',
'C' => 'Rank',
'D' => 'Link'
);
// Build headers
foreach( $cell_definition as $column => $value )
{
$objPHPExcel->getActiveSheet()->getColumnDimension("{$column}")->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
}
// Build cells
while( $rowCount < count($reportdetails) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value ) {
$objPHPExcel->getActiveSheet()->getRowDimension($rowCount + 2)->setRowHeight(35);
switch ($value) {
case 'BrandIcon':
if (file_exists($reportdetails[$rowCount][$value])) {
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Customer Signature');
$objDrawing->setDescription('Customer Signature');
//Path to signature .jpg file
$signature = $reportdetails[$rowCount][$value];
$objDrawing->setPath($signature);
$objDrawing->setOffsetX(25); //setOffsetX works properly
$objDrawing->setOffsetY(10); //setOffsetY works properly
$objDrawing->setCoordinates($column.$cell); //set image to cell
$objDrawing->setWidth(32);
$objDrawing->setHeight(32); //signature height
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //save
} else {
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, "Image not found" );
}
break;
case 'Link':
//set the value of the cell
$objPHPExcel->getActiveSheet()->SetCellValue($column.$cell, $reportdetails[$rowCount][$value]);
//change the data type of the cell
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->setDataType(PHPExcel_Cell_DataType::TYPE_STRING2);
///now set the link
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->getHyperlink()->setUrl(strip_tags($reportdetails[$rowCount][$value]));
break;
default:
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $reportdetails[$rowCount][$value] );
break;
}
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$saveExcelToLocalFile = saveExcelToLocalFile($objWriter);
$response = array(
'success' => true,
'filename' => $saveExcelToLocalFile['filename'],
'url' => $saveExcelToLocalFile['filePath']
);
echo json_encode($response);
die();
}
function saveExcelToLocalFile($objWriter) {
$rand = rand(1234, 9898);
$presentDate = date('YmdHis');
$fileName = "report_" . $rand . "_" . $presentDate . ".xlsx";
// make sure you have permission to write to directory
$filePath = SITEPATH . 'reports/' . $fileName;
$objWriter->save($filePath);
$data = array(
'filename' => $fileName,
'filePath' => $filePath
);
return $data;
}
?>
Here the $reportdetails contains the static array. How can I pass the mysql database value to the array dynamically? Please suggest any alternative other than phpexcel.

Drupal 7: How to send HTML Email

Could someone tell me what i am missing to send an HTML email using Drupal's function? Here is my call:
try{
drupal_mail('my_module', 'forgot', $node->field_email_address['und'][0]['value'], language_default(), array('reset_key' => $key),'do-not-reply#myemailaddress.com');
}catch(Exception $e){
print_r($e->getMessage());die();
}
And here is the function:
function my_module_mail($key, &$message, $params) {
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
// $headers = array(
// 'MIME-Version' => '1.0',
// 'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
// 'Content-Transfer-Encoding' => '8Bit',
// 'X-Mailer' => 'Drupal'
// );
// $message['headers'] = $headers;
$message['subject'] = 'Why wont this send html??';
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['body'][] = $body;
$message['from'] = 'do-not-reply#myemailaddress.com';
}
I tired just the html header and the full set that is commented out. What am I missing? The email sends fine but it's plain text. Thanks and let me know!
You can use this function
function my_module_custom_drupal_mail($target = NULL, $from = null, $subject, $message, $attachment = NULL){
$my_module = 'my_module';
$my_mail_token = microtime();
$message = array(
'id' => $my_module . '_' . $my_mail_token,
'to' => $target,
'subject' => $subject,
'body' => array($message),
'module' => $my_module,
'key' => $my_mail_token,
'from' => "$from <email#email.com>",
'headers' => array(
'From' => "$from <email#email.com>",
'Sender' => "$from <email#email.com>",
'Return-Path' => "$from <email#email.com>",
'Content-Type' => 'text/html; charset=utf-8'
),
);
if ($attachment) {
$file_content = file_get_contents($attachment[0]);
$message['params']['attachments'][] = array(
'filecontent' => $file_content,
'filename' => $attachment[1],
'filemime' => $attachment[2],
);
}
$system = drupal_mail_system($my_module, $my_mail_token);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
}
else {
return FALSE;
}
}
AND call it like :
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
$subject ='Why wont this send html??';
$from = 'myemail#email.com';
$sent = my_module_custom_drupal_mail($node->field_email_address['und'][0]['value'], $from, $subject, $body);
Customize it like you want ! :)
A few things need to be done:
/**
* Class SomeCustomModuleMailSystem Implements MailSystemInterface.
*
* Used to enable HTML email to be sent.
*/
class SomeCustomModuleMailSystem extends DefaultMailSystem {
public function format(array $message) {
$message['body'] = implode("\n\n", $message['body']);
$message['body'] = drupal_wrap_mail($message['body']);
return $message;
}
}
This to be done one time, so probably in a hook_enable or hook_update:
$current = variable_get('mail_system', ['default-system' => 'DefaultMailSystem']);
$addition = ['some_custom_module' => 'SomeCustomModuleMailSystem'];
variable_set('mail_system', array_merge($current, $addition));
Invoke hook_mail as normal, e.g.
/**
* Implements hook_mail().
*/
function some_custom_module_mail($key, &$message, $params) {
switch ($key) {
case 'some_mail_key':
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
Finally call it with something like this:
// Set variables required for the email.
$module = 'some_custom_module';
$key = 'some_mail_key';
$to = $email = 'thetoaddress#something.com';
$language = language_default();
$params['subject'] = 'Email subject';
$params['body'] = '<html><body>The HTML!</body></html>';
$from = 'thefromaddress#something.com';
$send = TRUE;
// Send the mail and log the result.
$result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
if ($result['result'] === TRUE) {
watchdog('some_custom_module', 'HTML email successfully sent.', [], WATCHDOG_INFO);
}
else {
watchdog('some_custom_module', 'HTML email failed to send', [], WATCHDOG_ERROR);
}

csv export not working with symfony 3

I try to do a csv export on my symfony project and i think that something is wrong because nothing happens and i have no error...??
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$response->setCallback(function() use ($customers){
$handle = fopen('php://output', 'w+');
// Nom des colonnes du CSV
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
//Champs
foreach ($customers as $index => $customer)
{
//dump($client);die();
fputcsv($handle,array(
$customer->getName(),
$customer->getAdress(),
$customer->getCity(),
$customer->getCode(),
),';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8', 'application/force-download');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);
return $response;
}
I call this function in my controler like this:
if (isset($_POST['export']))
{
$export = $exp->exportCsv($customers);
}
Have you any idea, please???
If you want to see what happened in your streamed response and what is the error, you just have to call the callback function outside the response.
$callback = function() use ($customers){
$handle = fopen('php://output', 'w+');
// Nom des colonnes du CSV
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
//Champs
foreach ($customers as $index => $customer)
{
//dump($client);die();
fputcsv($handle,array(
$customer->getName(),
$customer->getAdress(),
$customer->getCity(),
$customer->getCode(),
),';');
}
fclose($handle);
};
$callback();exit;
And after just delete the last line and insert the callback function inside the StreamedResponse object $response->setCallback($callback);

Incorrect password encryption

I have a small password encryption problem ^^
in my database the passwords are present, and have to present, in this form:
VwBybV5ATQ9RkdvvVZNOlldEEDU9tDjttju7t8l+HeVe4nskHeMpbuCoQsqqORUQKZ1pg7gGtFocpkSIw8N9kA==
and right now I have a function that needs to generate a password for me. Unfortunately the encryption is not good, because that's what I get:
YmY1NzFkM2VkODYwOGQ1OWFlMTRiZDVkOTc3ZDFkNzQ0ODIzN2U5NWMzNzU0ZjI1Y2U4MTZhYzBiYmExYWJjZTg2Y2JjNzYyM2QwYTJmMDUwYWJiMzQxMjliYjBjYWQxMGZiMzliYzk3OGQwZjYxMGU3Y2E0NjE0ZTkxYzFiYmM=
my code :
public function lostpasswordAction(Request $request)
{
$success = '';
$string = '';
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$max = strlen($characters) - 1;
for ($i = 0; $i < 12; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
if ($request->request->get('email') !== null) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationSonataUserBundle:User')->findByEmail($request->request->get('email'));
if (is_null($user)) {
$response = new JsonResponse('Not Found');
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
$login = $user[0]->getEmail();
$password = $string;
$user[0]->setPassword(hash('sha512',$password));
$em->persist($user[0]);
$em->flush();
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom('no-reply#noreply.com')
->setTo($request->request->get('email'))
->setBody(
$this->renderView(
'emails/lostpassword.txt.twig',
array(
'login' => $login,
'password' => $password
)
),
'text/plain'
);
$return = $this->get('mailer')->send($message);
$success = 'Email sent';
return new JsonResponse($success);
}
$response = new JsonResponse('POST only');
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
return $response;
}
Can someone help me so I get the right shape please?
Thank you in advance

export csv catch null value symfony 2

I have some troubles with an export to csv. In my table I have some null value and I can't find out how to catch them.
public function exportCSVAction()
{
$results = $this->getDoctrine()->getManager()
->getRepository('MyRepoBundle:Cronexecution')->findAll();
$response = new StreamedResponse();
$response->setCallback(
function () use ($results) {
$handle = fopen('php://output', 'r+');
foreach ($results as $row) {
if (!($row->getNbLineIn()) && !($row->getNbLineOut())) {
$delContact = (($row->getNbLineIn()) - ($row->getNbLineOut()));
}
else{
$delContact="Unknown";
}
$data = array(
$row->getClient(),
$row->getDealingName(),
$row->$delContact,
);
fputcsv($handle, $data);
}
fclose($handle);
}
);
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;
}
When I delete the $row->$delContact the csv export work cause there isn't null value but when I let it I got a "This site can’t be reached" error.
So I tried to catch when it's null with 2 or 3 different method but impossible to figure it out.
Thanks for your help
Change according to bellow code :
$data = array(
$row->getClient(),
$row->getDealingName(),
$delContact,
);

Resources