PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 5, 2022

[FIXED] How to make PHPExcel download work through <a> element?

 October 05, 2022     phpexcel, symfony, twig     No comments   

Issue

I wrote some code to generate an excel (.xlsx) file for users to download on my website. I'm using Symfony2, although I don't think it is the reason I'm having this problem. Here is a snippet of my code:

$filename = "cmm_payment_report.xlsx";

header('Content-Type: application/vnd.ms-excel');
header(sprintf('Content-Disposition: attachment; filename="%s"', $filename));
header("Cache-Control: max-age=0");

$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$objWriter->save("php://output");

If I open a new page and paste the link for this download into the browser, it works as normal and I'm able to download the file. However, if I put the link into a Twig template like so:

<a href="{{ path('report_payment_excel', {payPeriod: app.request.get('pay-period')}) }}" target="_blank">
    <button>Download as XLS</button>
</a>

it doesn't work. I click on the link and the browser indicates that it's loading, however nothing happens after it stops loading. If I right-click > open link in new tab, then it works. Adding target="_blank" doesn't fix the problem.


Solution

The problem was that my <button>Download as XLS</button> element was contained inside of a <form> element, so it was inadvertently submitting the form instead of following the link.



Answered By - Robert Calove
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing