How to remove html code in excel downloads using phpspreadsheet with wordpress plugins shortcode

OK, so you have some PHP code that will return binary data and you want to use it.

So if you want to return only that binary data, then you can’t but it inside a page as a shortcode. Shortcodes are printed as article content, so all other parts of page will be printed also (header, navigation menus, and so on).

So there are 2 solutions:

  1. Changing the way you want to do this
  2. Cheating and using Output Buffering (but it’s not a nice solution).

1. Printing the content earlier

The best solution would be to use template_redirect hook (or some other early hook) and printing all the contents in there.

The only problem is that you have to know, what file should be printed, so you’ll have to put that info as meta values to the post, and not as a shortcode.

add_action( 'template_redirect', function () {
    if ( <CONDITION> ) { // check if excel file should be printed
        // put your excel printing code in here
    }
} );

2. Output buffering

The other way (but not very nice one) would be to start buffering before any content gets printed and discard anything that gets printed before the shortcode.

add_action( 'init', function () {
    ob_start();
} );

add_action( 'wp_footer', function () {
    ob_end_flush();
} );

And in your shortcode:

ob_end_clean();
// the rest of your code