0

I wrote PHP code in order to export one table in csv (excel). My table has 6 columns: Timestamp, Order number, Last Name, First Name, Phone number, e-mail address. The character set is utf8. My code is:

<?php
$conn = mysqli_connect("localhost", "username", "password", "database");

$filename = "FILENAME";
$fp = fopen('php://output', 'w');

$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='mydatabase' AND TABLE_NAME='myTableName'";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_row($result)) {
    $header[] = $row[0];
}   

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);

$query = "SELECT * FROM `MyTableName` order by `LNAME`";

$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_row($result)) {
    fputcsv($fp, $row);
}
exit;
?>

So, I have my excel file but, unfortunately, some names are written in greek language and I see in my export file characters like "ΣΟΦΙΑ".

Could somebody help me to solve this problem.

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26

3 Answers3

0

This is an encoding issue, use charset=UTF-8 in the header as shown below:

Replace this line :

header('Content-type: application/csv');

With this line :

header("content-type:application/csv;charset=UTF-8");
Prabhjot Singh Kainth
  • 1,831
  • 2
  • 18
  • 26
0

Thank you, I tried it without success. The export file has the same result. I'm not a programmer and my knowledge in php and sql is poor. But I find a workaround. I tried this:

    <?php

        $con = mysqli_connect("localhost", "MyUsername", "MyPassword", "MyDatabase");
        if (mysqli_connect_errno())
        {
            die('Could not connect: ' . mysqli_connect_error());
        }

        mysqli_select_db($con,"MyDatabase");       

    $sql = "SELECT * FROM `MyTableName` order by `LNAME`";

    $result = mysqli_query($con, $sql);


            while($row = mysqli_fetch_array($result))
            {
          echo ("<ul>");
          echo ("<li>" . utf8_decode($row['LNAME']) . "&nbsp;" . utf8_decode($row['FNAME']) . "&nbsp;" . $row['PHONE'] . "&nbsp;" . utf8_decode($row['EMAIL'])."</li>");
              echo ("</ul>");
                         }

        mysqli_close($con);
?>  

So, as a result I have a webpage list with all names and characters readable. Although, I cannot think how to use "utf8_decode" in order to have the same result with a csv file. Any ideas?

0

Are you opening the CSV file in Excel? This post describes how to add a UTF-8 Byte Order Mark (BOM) to the file so Excel 2007 and later will correctly recognize the encoding: Microsoft Excel mangles Diacritics in .csv files?

kmoser
  • 8,780
  • 3
  • 24
  • 40