Hi guys,
My website let user download their records from database and some record contain Chinese characters. My code are likes below:
class DBConnection {
private $con = null;
private $host = 'localhost';
private $connection_string = 'mysql:host=www.twitext.com;dbname=twitext';
private $username = 'twitext';
private $dbname = 'twitext';
private $password = 'password';
function __construct() {
}
public function getConnection(){
if($this->con == null){
try {
$this->con = new PDO($this->connection_string, $this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
error_log($e->getMessage());
}
}
return $this->con;
}
function closeConnection(){
$this->con = null;
}
public function getHost(){
return $this->host;
}
public function getUsername(){
return $this->username;
}
public function getPassword(){
return $this->password;
}
public function getDbname(){
return $this->dbname;
}
}
function getAllUserContact() {
$data = array();
$conn = new DBConnection();
$err_code = null;
try{
$stmt = $conn->getConnection()->prepare('SET character_set_results=utf8');
$stmt->execute();
$stmt = $conn->getConnection()->prepare('SET character_set_connection=utf8');
$stmt->execute();
$sql = '........'; // too long .....
$stmt = $conn->getConnection()->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch()) {
$data[] = array($row['contact_id'], $row['dialling_code'], $row['mobile_num'], $row['email'], $row['name']);
}
} catch(PDOException $e) {
error_log($e->getMessage());
}
$stmt->closeCursor();
$conn->closeConnection();
return $data;
}
$filename = 'contacts.csv';
$csv_terminated = "\n";
$out = '"Date Added",' . '"Name",' . '"Email",' . '"Sex",' . '"Remark"';
$out .= $csv_terminated;
foreach($result as $record){
$out .= '"' . $contact->date_created . $contact->name . '","' . $contact->email . '","' . $contact->sex . '","' . $contact->remark . '"';
$out .= $csv_terminated;
}
Appreciate any advice please. Thanks !
regards,
Mark Thien
$result = $user_contact_manager->getAllUserContact();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
header("Content-type: text/x-csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
Chinese character in downloaded file becomes garble
Moderator: General Moderators
Re: Chinese character in downloaded file becomes garble
If the characters aren't in UTF-8 then you'll see mojibake.
Before they get stored in the database you need to convert them from whatever encoding they're in to UTF-8.
Before they get stored in the database you need to convert them from whatever encoding they're in to UTF-8.