Search code examples
phpexport-to-excel

How to display data that is with UTF-8 character while exporting it to .xls (EXCEL) file


<?php
$month=$_REQUEST["month"];
include 'include/myfunc.php';
$sql = "SELECT * FROM announcement WHERE month='".$month."'";
$result = mysqli_query($con,$sql);
$status="";
$html='<table><tr><td>Date</td><td>Announcement Detail</td><td>Tag</td><td>Amount</td><td>Status</td><td>File Name</td></tr>' ;

while( $row = mysqli_fetch_array($result) )
{
    if ($row['status']=="active") {
      $status = "निरकर्त";
    }else{
        $status = "लंबित";
    }
    
    $html.='<tr><td>'.$row['date'].' '.$row['month'].' '.$row['year'].'</td><td>'.$row['announcement_detail'].'</td><td>'.$row['tag'].'</td><td>'.$row['amount'].'</td><td>'.$status.'</td><td>'.$row['file'].'</td></tr>' ;
}
$html.= '</table>';
header('Content-Type:application/xls');
header('Content-Disposition:attachment;filename=report.xls');

echo $html;
?>

When exported, it is showing something like this निरकरà¥à¤¤ I have tried putting in this header("content-type:application/xls;charset=UTF-8"); Still m getting only the garbage value. Can anyone help me on what exactly I should do so that data displays properly irrespective of whether user has stored data in English or Hindi.


Solution

  • Instead of doing echo you have convert it like this and it will work.

    print chr(255) . chr(254) . mb_convert_encoding($html, 'UTF-16LE', 'UTF-8');