Jonathan Lafleur
Jonathan Lafleur

Reputation: 493

UTF-8 dates doesn't encode properly

I have hard time with character charset, I suspect my fonction that display date to return non UTF-8 character (août is replaced by a question mark inside a diamond août).

When working on my local server everything's fine but when I push my code on my staging server, it's not displaying properly.

Here is the part I suspect causing problem :

$langCode = "fr_FR"; /* Alos tried  fr_FR.UTF-8 */
setlocale(LC_ALL, $langCode);
$monthName = _(strftime("%B",strtotime($dateStr)))
echo $monthName; /* Alos tried  utf8_encode($monthName) worked on my staging server but not on my local server ! I'm using  */

Upvotes: 2

Views: 2751

Answers (4)

Jonathan Lafleur
Jonathan Lafleur

Reputation: 493

Finally found how to find the bug and fix it.

setlocale(LC_ALL, 'fr_FR');

var_dump(mb_detect_encoding(_(strftime("%B",strtotime($dateStr)))));

the dump returned UTF-8 on local and FALSE on staging server.

PHP.net documentation about mb_detect_encoding()

Return Values

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

So charset can't be detected. I will try to force it "again"

setlocale(LC_ALL, 'fr_FR.UTF-8');

var_dump(mb_detect_encoding(_(strftime("%B",strtotime($dateStr)))));

this time the dump returned UTF-8 on local and UTF-8 on staging server. So I rollback my code to see what's happened when I tried first time with fr_FR.UTF-8 why does it was not working ? And I realize I was using utf8_encode() like pointed by user deceze in comment of this function's doc,

In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

Thank you for your help everyone !

Upvotes: 2

Bahrami-Reza
Bahrami-Reza

Reputation: 608

you need to use :

  <?php
  $conn = mysql_connect("localhost","root","root");
  mysql_select_db("test");

  mysql_query("SET NAMES 'utf8'", $conn);//put this line after you select db.

Upvotes: 0

VMai
VMai

Reputation: 10336

It seems your server are configured to send the header

content-type: text/html; charset=UTF-8

as default. You could change your server configuration or you could add at the very start

<?php
    header("content-type: text/html; charset=UTF-8");
?>

to set this header by yourself.

Upvotes: 0

Khalid
Khalid

Reputation: 4808

put this meta tag on your html code inside <head></head>

<meta charset="UTF-8">

Upvotes: 0

Related Questions