Jump to content

Chinese character in downloaded file becomes garble


markthien

Recommended Posts

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.