Reputation: 17
I am exporting a excel sheet using php script and my code is
<?php
function excel_file(){
header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", "w");
foreach ($tabledata as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
}
?>
HTML
<input type="button" name="excel_file" onclick="<?php excel_file(); ?>" value="Download File">
Problem is this:
This function excel_file()
execute on loading the page not on click.
The excel file which i get, includes the data of whole page not the data of that perticular array "$tabledata
"
Upvotes: 1
Views: 6087
Reputation: 1258
You include in your button the output of the function. You cannot combine a javascript onclick with a php function.
HTML:
<a href="your_url.php?action=xls">Excel</a>
Then in your code
if(isset($_GET['action']) && $_GET['action'] == 'xls')
{
excel_file();
exit;
}
In this way you click on the Excel link and send that action to the server.
You catch with PHP the $_GET['action']
and call the excel_file()
function.
Upvotes: 2