1

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:

  1. This function excel_file() execute on loading the page not on click.

  2. The excel file which i get, includes the data of whole page not the data of that perticular array "$tabledata"

2
  • $tabledata isn't available in the scope of your excel_file() function, and you need to suppress outputting your html markup if you're outputting the CSV Commented May 27, 2014 at 9:34
  • i am not getting your 2nd point Commented May 27, 2014 at 9:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@MarkBaker I don't see the error here or I am really confused on the moment.. Please clarify the error you see.
in my case now its working... i am using <form name="form_name" method="post" action=""><input type="submit" value="Download Excel" name ="submit" /></form> .. as my php code is on same page :)
@Stefan - there's always days like that :)
This would bring up the prompt to download? /* that is the reason I am viewing this question */
Also, is there a way to POST to that URL, instead of using query string?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.