Home » excel » Error exporting to excel in PHP

Error exporting to excel in PHP

Posted by: admin May 14, 2020 Leave a comment


When I execute this:

        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=test.xls");
        header("Pragma: no-cache");
        header("Expires: 0");

       $flag = false;

       foreach($data as $row) {

         if(!$flag) {
           echo implode("\t", array_keys($row)) . "\n";
           $flag = true;
        array_walk($row, __NAMESPACE__ . '\cleanData');
        echo implode("\t", array_values($row)) . "\n";

I got error like below when am opening the downloaded .xls file.

The file You are trying to open Facemappsoft.xls is in a different format than file extension

Can any one help me to resolve this right now?

How to&Answers:

You are generating a tab-separated values file and giving it a Excel 97-2003 compatible file extension (*.xls).

Excel is complaining about this mismatch when opening the file.

To fix the issue, you will need to give the file an appropriate extension (*.tsv) and update the Content-Type header to one properly describing the file format, such as:

Content-Type: text/tab-separated-values