-1

I want to export my mysql data to an excel file, I have done it but if I have Greek words they appear with nonsense characters. So I believe I have to add some encoding headers but I didn't found something.

Here is my code:

<?php  
//export.php  
$pdo = Database::connect();
$output = '';

 $query = "SELECT * FROM clients";
 $stmt = $pdo->prepare($query);
 //Execute the statement.
 $stmt->execute();
 $clients= $stmt->fetchAll();

  $output .= '
   <table class="table" bordered="1">  
    <tr>  
        <th>Ονοματεπώνυμο</th>
        <th>Σταθερό Τηλέφωνο</th>
        <th>Email</th>
        <th>Διεύθυνση</th>  

    </tr>
  ';
  foreach($clients as $items):
   $output .= "
    <tr>
      <td>".$items['fullname']."</td>
      <td>".$items['phone1']."</td>
      <td>".$items['email']."</td>
      <td>".$items['address']."</td>

    </tr>
   ";
  endforeach;
  $output .= '</table>';
  header('Content-Type: application/xls');
  header('Default-Charset :   utf-8 ');
  header('Content-Disposition: attachment; filename=download.xls');
  echo $output;



?>

I don't mind to change the whole code if you got something better to show me. Thanks in advance

Shadow
  • 33,525
  • 10
  • 51
  • 64
mike vorisis
  • 2,786
  • 6
  • 40
  • 74
  • 1
    As you're creating html markup rather than a native-format excel file, you need to specify headers with a charset, and rely on the Excel importer to interpret it correctly – Mark Baker Dec 16 '17 at 23:51
  • And the content type for an Excel file isn't `application/xls` but `application/vnd.ms-excel` (for xls files) – Mark Baker Dec 16 '17 at 23:52
  • @MarkBaker `header('Default-Charset : utf-8 ');` is this wrong for setting charset because I put it thinking that might work – mike vorisis Dec 16 '17 at 23:54
  • Not the http request headers; MS Excel doesn't read those at all; the html header – Mark Baker Dec 16 '17 at 23:57
  • Your alternative is to create a genuine BIFF-format (xls) or OfficeOpenXML (xlsx) file using a library like PHPExcel – Mark Baker Dec 16 '17 at 23:58

1 Answers1

1

That's not really how it works. You can't just take some html code for a table, slap a .xls extension onto it and open it in Excel. You need a library to handle this for you. Have a look for example at these two: