简体   繁体   中英

xls file php download is in a different format than specified by the file extension

I'm struggling with my XML to XLS code in PHP.
I have PHP code that exports MySql data to XML and I have code that writes XML to XLS.
This all works fine, except that when I open the xls file, I get an error:

"The file you are trying to open is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"

my code:

<?php
$file = 'filename';
$url = "$file.xml"; // from xml file
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$file.xls" ); // to xls file

if (file_exists($url)) {
    $xml = simplexml_load_file($url);

    echo 'Voornaam'."\t" . 'Achternaam'."\t" . 'Geslacht'."\t" . 'Instrument'."\t\n";
    foreach($xml->lid as $lid)
    {
        echo $lid->voornaam."\t" . $lid->achternaam."\t" . $lid->geslacht."\t" . $lid->instrument."\n";
    }
}
?>

I found that it has something to do with the MIME_Types
https://filext.com/faq/office_mime_types.php

The header("Content-Type: application/vnd.ms-excel"); is for the older versions of excel. But when I use the xlsx type, the file won't open at all.

Like I said, this code runs fine, downloads the Excel file in xls format to my computer. But how can I open it without the error?

I would also like to upgrade the file to xlsx format if someonw knows how to open the file in that format.

Well, your header and filename are both saying "this is an XLS file" - but it isn't, it's actually a TSV file (Tab-Separated Values). So yes, the message is accurate: the file extension is misleading.

To write an actual, valid XLS (or XLSX), it is easiest to use a library which does this for you - both these formats are complex and tricky. I've had best results using PhpExcel ( example code ).

When Excel opens an .xls file, it expects it to be in normal old binary Excel format. You seem to be outputting tab separated text (.tsv format), which Excel understands but doesn't want to open without issuing a warning. I think this warning was introduced with Excel 2007, and that earlier versions opened happily without warnings. Unfortunately I have no sources handy for this info, only personal experience.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM