This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 9 years ago.
I have a table that includes special characters such as ™.
This character can be entered and viewed using phpMyAdmin and other software, but when I use a SELECT statement in PHP to output to a browser, I get the diamond with question mark in it.
The table type is MyISAM. The encoding is UTF-8 Unicode. The collation is utf8_unicode_ci.
The first line of the html head is
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
I tried using the htmlentities() function on the string before outputting it. No luck.
I also tried adding this to php before any output (no difference):
header('Content-type: text/html; charset=utf-8');
Lastly I tried adding this right below the initial mysql connection (this resulted in additional odd characters being displayed):
$db_charset = mysql_set_charset('utf8',$db);
What have I missed?
Below code works for me.
$sql = "SELECT * FROM chartest";
mysql_set_charset("UTF8");
$rs = mysql_query($sql);
header('Content-type: text/html; charset=utf-8');
while ($row = mysql_fetch_array($rs)) {
echo $row['name'];
}
There are a couple things that might help. First, even though you're setting the charset to UTF-8 in the header, that might not be enough. I've seen the browser ignore that before. Try forcing it by adding this in the head of your html:
<meta charset='utf-8'>
Next, as mentioned here, try doing this:
mysql_query ("set character_set_client='utf8'");
mysql_query ("set character_set_results='utf8'");
mysql_query ("set collation_connection='utf8_general_ci'");
EDIT
So I've just done some reading up an playing around a bit. First let me tell you, despite what I mentioned in the comments, utf8_encode() and utf8_decode() will not help you here. It helps to actually understand UTF-8 encoding. I found the Wikipedia page on UTF-8 very helpful. Assuming the value you are getting back from the database is in fact already UTF-8 encoded and you simply dump it out right after getting it then it should be fine.
If you are doing anything with the database result (manipulating the string in any way especially) and you don't use the unicode aware functions from the PHP mbstring library then it will probably mess it up since the standard PHP string functions are not unicode aware.
Once you understand how UTF-8 encoding works you can do something cool like this:
$test = "™";
for($i = 0; $i < strlen($test); $i++) {
echo sprintf("%b ", ord($test[$i]));
}
Which dumps out something like this:
11100010 10000100 10100010
That's a properly encoded UTF-8 '™' character. If you don't have a character like that in your data retrieved from the database then something is messed up.
To check, try searching for a special character that you know is in the result using mb_strpos():
var_dump(mb_strpos($db_result, '™'));
If that returns anything other than false then the data from the database is fine, otherwise we can at least establish that it's a problem between PHP and the database.
you need to execute the following query first.
mysql_query("SET NAMES utf8");
Related
So I'm trying to find a fast way to show all my results from my database, but I can't seem to figure out why I need to add the utf8_encode() function to all of my text in order to show all my characters properly.
For the record, my database information is both French and English, so I will need special characters including à, ç, è, é, ê, î, ö, ô, ù (and more).
My form's page has the following tag:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
My database, all my tables and all my fields are set to utf8_general_ci.
When I want to echo the database information onto the page, I use this query:
public function read_information()
{
global $db;
$query = "SELECT * FROM table WHERE id='1' LIMIT 1";
return $db->select($query);
}
and return the information like so:
$info = $query->read_information();
<?php foreach ( $info as $dbinfo ) { ?>
<pre><?php echo $dbinfo->column; ?></pre>
<?php } ?>
However, if I have French characters in my string, I need to <pre><?php echo utf8_encode($info->column); ?></pre>, and this is something I really want to avoid.
I have read up the documentation on PHP.net regarding utf8_encode/utf8_decode, htmlentities/html_entity_decode and quite a few more. However, I can't seem to figure out why I need to add a special function for every database result.
I have also tried using mysqli_query("SET NAMES 'utf8'", $mysqli); but this doesn't solve my problem. I guess what I'm looking for is some kind of shortcut where I don't have to create a function like make_this_french_friendly() type of thing.
Ensure all the stack you are working with is set to UTF8 from db, web server, page meta etc
checking things like
ini_set('default_charset', 'utf-8')
should output simple stuff then in my experience
As #deceze pointed out, this thread provided proper insight using $mysqli->set_charset('utf8');.
Maybe use UTF-8 without BOM encoding for your file?
header('Content-type: text/html; charset=utf-8');
... in PHP (you can also do it with "ini_set()" function) and:
<meta charset="utf-8">
... in HTML.
You have also to set the right encoding for you database tables.
Possible duplicate of "GET" method encoding French characters incorrectly in PHP
Maybe your text coding is not be UTF-8.
Please look: What's different between UTF-8 and UTF-8 without BOM?
Maybe it can helps you.
My brain hurts, so I need help to solve this issue. I have read about many similar encoding problems but I can't find any info that helps me with this particular issue.
I have a PHP service which reads data from database. It sets the charset to:
mysql_set_charset('utf8', $con)
Basically it then executes a query and loops thru the db items like this:
while($row = mysql_fetch_object($result)) {
$row->MyField1 = utf8_encode($row->MyField1);
$row->MyField2 = utf8_encode($row->MyField2);
...
$res[] = $row;
}
and ends with:
print json_encode($res);
I then read the data from Ruby (a sinatra app) with:
uri = URI(str)
source = Net::HTTP.get(uri)
src = JSON.parse(source)
src.each do |s|
# Display s.MyField1 in HTML here.... HTML page is HTML5 and <meta charset="utf-8">
end
The problem is that I display strings like:
ALLMÃNHETENS ÃKNING
where 'Ã' is some unknown character to me. It should properly be 'Ä' in the first occurrence and 'Å' (Swedish A with 'ring diacritic' http://en.wikipedia.org/wiki/Ring_(diacritic)).
Is it the PHP code that is wrong? Or the Ruby code? If anyone could point me in the right direction I would be very grateful? Frankly I don't know where to start chasing bugs.
OK It seems the answer is very accurately described here:
http://www.i18nqa.com/debug/bug-utf-8-latin1.html
And the important thing is that my PHP-script must add:
Content-type: application/json; charset=utf-8
otherwise the UTF-8 will have their individual bytes interpreted as ISO-8859-1 or Windows-1252 causing exactly the described bevahiour above.
IMPORTANT ADDITION: I also had to remove the utf8_encode() call in the PHP-script since the data already was UTF-8 encoded (or maybe the mysql_set_charset("utf8", $con) did that thing, I don't know).
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 3 months ago.
Im trying to insert 汉语/漢語 characters into my database but im only getting ????? when i do. Iv look at loads of information on line but no solution works. When i run an insert query in my db with the characters 汉语/漢語 it works, so I know my db is set-up for utf8...Its somthing im doing in my PHP file that's the problem...any help would be greatly appreciated.
<?php
include 'config.php';
header('Content-Type:text/html; charset=UTF-8');
mysqli_query("SET NAMES utf8");
mysqli_set_charset('utf8');
// check for required fields
if (isset($_POST['name'])) {
$name = mysqli_real_escape_string($link, $_POST['name']);
$result = mysqli_query($link, "INSERT INTO scores(`id` , `name`)VALUES(NULL, '$name'");
You need to make sure your database is operating in UTF-8 mode. You need to do this on the table itself. You said you INSERTED the string, but did you check to see if you can read it back out? As noted in my comment below, you should be sure that you're connecting to MySQL with UTF-8 enabled. There is more information in the answer below:
How to make MySQL handle UTF-8 properly
Additionally, be sure that the PHP file itself is being saved in UTF-8 format. Last but not least ensure the HTML page is correctly set to use utf-8:
<meta charset="utf-8"> vs <meta http-equiv="Content-Type">
Here's an old cheat sheet I rely on. Keep mind that some of this info is out of date
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
// only for legacy MySQL_query
mysql_set_charset('utf8',$con);
// only for MySQLi
$mysqli->set_charset("utf8")
also check out:
http://tympanus.net/codrops/2009/08/31/solving-php-mysql-utf-8-issues/
PHP didn't use to be natively UTF-8 friendly, you had to rely on secondary functions like these below. I'm pretty sure all of the functions on the left have become UTF-8 friendly for a few years now.
mail() -> mb_send_mail()
strlen() -> mb_strlen()
strpos() -> mb_strpos()
strrpos() -> mb_strrpos()
substr() -> mb_substr()
strtolower() -> mb_strtolower()
strtoupper() -> mb_strtoupper()
substr_count() -> mb_substr_count()
htmlentities($var) -> htmlentities($var, ENT_QUOTES, 'UTF-8')
I'm working with UTF-8 encoding in PHP and I keep managing to get the output just as I want it. And then without anything happening with the code, the output all of a sudden changes.
Previously I was getting hebrew output. Now I'm getting "&&&&&".
Any ideas what might be causing this?
These are most common problems:
Your editor that you’re creating the PHP/HTML files in
The web browser you are viewing your site through
Your PHP web application running on the web server
The MySQL database
Anywhere else external you’re reading/writing data from (memcached, APIs, RSS feeds, etc)
And few things you can try:
Configuring your editor
Ensure that your text editor, IDE or whatever you’re writing the PHP code in saves your files in UTF-8 format. Your FTP client, scp, SFTP client doesn’t need any special UTF-8 setting.
Making sure that web browsers know to use UTF-8
To make sure your users’ browsers all know to read/write all data as UTF-8 you can set this in two places.
The content-type tag
Ensure the content-type META header specifies UTF-8 as the character set like this:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
The HTTP response headers
Make sure that the Content-Type response header also specifies UTF-8 as the character-set like this:
ini_set('default_charset', 'utf-8')
Configuring the MySQL Connection
Now you know that all of the data you’re receiving from the users is in UTF-8 format we need to configure the client connection between the PHP and the MySQL database.
There’s a generic way of doing by simply executing the MySQL query:
SET NAMES utf8;
…and depending on which client/driver you’re using there are helper functions to do this more easily instead:
With the built in mysql functions
mysql_set_charset('utf8', $link);
With MySQLi
$mysqli->set_charset("utf8")
*With PDO_MySQL (as you connect)*
$pdo = new PDO(
'mysql:host=hostname;dbname=defaultDbName',
'username',
'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
The MySQL Database
We’re pretty much there now, you just need to make sure that MySQL knows to store the data in your tables as UTF-8. You can check their encoding by looking at the Collation value in the output of SHOW TABLE STATUS (in phpmyadmin this is shown in the list of tables).
If your tables are not already in UTF-8 (it’s likely they’re in latin1) then you’ll need to convert them by running the following command for each table:
ALTER TABLE myTable CHARACTER SET utf8 COLLATE utf8_general_ci;
One last thing to watch out for
With all of these steps complete now your application should be free of any character set problems.
There is one thing to watch out for, most of the PHP string functions are not unicode aware so for example if you run strlen() against a multi-byte character it’ll return the number of bytes in the input, not the number of characters. You can work round this by using the Multibyte String PHP extension though it’s not that common for these byte/character issues to cause problems.
Taken form here: http://webmonkeyuk.wordpress.com/2011/04/23/how-to-avoid-character-encoding-problems-in-php/
Try after setting the content type with header like this
header('Content-Type: text/html; charset=utf-8');
Try this function - >
$html = "Bla Bla Bla...";
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
for more - http://php.net/manual/en/function.mb-convert-encoding.php
I put together this method and called it in the file I'm working with, and that seemed to resolve the issue.
function setutf_8()
{
header('content-type: text/html; charset: utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
}
Thank you for all your help! :)
i'm running a german website which gets content from a mysql database.
i've defined the charset as utf8 as following:
<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />
the problem is, when fetching + displaying contents from the database i always need to use utf8_encode in order to get the proper german "umlauts".
i want to maintain the utf8 charset for my web as i'll have to add more languages which have special characters.
any ideas on how to 1:1 echo database contents without having to utf8_encode?
thanks
Hard to tell without seeing how you are connecting to your database, but a common problem is the database connection itself.
After opening / selecting the database you need to set:
$db->exec('SET CHARACTER SET utf8'); // PDO
mysql_set_charset('utf8'); // Deprecated mysql_* extension
Whenever I want to use utf-8 with PHP and MySQL, I found that usually these two functions are the ones you should use after mysql_connect():
mysql_set_charset('utf8', $link);
mysql_query('SET NAMES utf8', $link);
Setting the content type in the header may do the trick:
header('content-type: text/html; charset=utf-8');
I had a similar problem and i solve adding this in the beginning of my PHP file:
ini_set('default_charset', 'UTF-8');
mb_internal_encoding('UTF-8');
Additionally, is very important to check if you are saving your PHP file in UTF-8 format without BOM, i had a big headache with this. I recomend Notepad++, it shows the current file encoding and allow you to convert to UTF-8 without BOM if necessary.
If you would like to see my problem and solution, it is here.
Hope it can help you!