Jim Hommes
Jim Hommes

Reputation: 41

PHPSpreadsheet in Wordpress generates corrupt files with plaintext PHP

I'm developing a Wordpress plugin and I'm trying to create a button that creates an Excel export. I've been trying to find the ideal Wordpress method for this, and so far I've come up with this. This is the button:

<form method="post" action="">
    <input type="submit" name="export_excel"  value="Maak een Excel export" class="button-primary"/>
</form>

And this is the function I hooked into admin_init.

add_action("admin_init", "export_excel");


function export_excel() {

if (isset($_POST['export_excel'])) {


    try {
        $filename = 'test.xlsx';

        ob_clean();
        header( 'Pragma: public' );
        header( 'Expires: 0' );
        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
        header( 'Cache-Control: private', false );
        header( 'Content-Type: application/vnd.ms-excel' );
        header( 'Content-Disposition: attachment;filename=' . $filename );

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Hello World !');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        ob_flush();

    } catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
    }
}

}

When I click the button it downloads an Excel file correctly, but afterwards it posts the entire wp_admin php plaintext, making the file corrupt. I'm assuming Wordpress does this somewhere, but I haven't been able to find out how. I'd appreciate any help with this!

Besides that, I was wondering why my page was working while my function that's added to admin_init is missing the exit statement (why isn't all other code shoved?). I got a whitescreen on loading any admin page when it did contain the exit statement.

Thanks!

Upvotes: 2

Views: 3367

Answers (2)

Jim Hommes
Jim Hommes

Reputation: 41

I've fixed it by placing the exit statement in the if statement. I removed it earlier because it was breaking the page, not realising that outside of the if statement Wordpress exits itself.

Upvotes: 2

bigwolk
bigwolk

Reputation: 418

$writer->save('php://output'); - there should be name of file, for example: $writer->save('hello world.xlsx');

Upvotes: -1

Related Questions