I have a PHP object displaying values as below when I use var_dump($obj):
object() (1) { ["name"]=> string(3) "Lê" ... }
But when I print $obj->name, the browser displays "Lê" instead.
My browser is displaying UTF-8.
HTML charset is also set to utf-8.
I tried with some functions but I didn't solve this.
could you please help me to solve this issue? Thanks.
EDIT:
I have already had all checked items as below:
header('Content-Type: text/html; charset=utf-8');
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
My browser is displaying UTF-8
The $obj is get from db table which set "character set" to utf-8 and "collation" to utf8_general_ci
PHP file is encoded to UTF-8
Set a UTF-8 header('Content-Type: text/html; charset=utf-8');.
I've just tested this on PHP5.4.8, nginx, Ubuntu 12.04 and Firefox. AFAIK, you'll get the same results in pretty much any PHP stack from at least the past 5 years.
<?php
$mystring = 'Lê';
print $mystring;
output:
Lê
<?php
header('Content-Type: text/html; charset=utf-8');
$mystring = 'Lê';
print $mystring;
output:
Lê
Related
I'm trying to get data from Python script:
import pymorphy2
import json
import sys
morph = pymorphy2.MorphAnalyzer()
butyavka = morph.parse(sys.argv[1])[0]
for item in butyavka.lexeme:
print(item.word)
PHP code:
<?php
chdir('C:\\Users\Michael-PC\AppData\Local\Programs\Python\Python35-32');
$out;
passthru('python WordAnalizator.py "слово"', $out);
echo($out);
?>
If I use console, it make correct response, like:
But in PHP I have only first word:
Whats wrong?
This is obvious encoding problem (Russian letters become unreadable). So, try to set (i.e. change default) encoding in the PHP code, e.g. add to header usage of Unicode:
header('Content-Type: text/html; charset=utf-8');
If charset=utf-8 does not help, try charset=windows-1251 instead.
UPDATE:
Do not forget to save your file (PHP code in UTF encoding for utf-8, or ANSI for windows-1251)
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.
My php files are saved as UTF-8 NO BOM
If I inspect my output page, headers indicate UTF-8.
My local machine is a Mac with MAMP installed and my stating server have CentOS with cPanel installed.
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 */
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 !
put this meta tag on your html code inside <head></head>
<meta charset="UTF-8">
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.
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.
I wrote a simple script below to simulate my problem.
Both my string and pattern contain unicode characters.
Basically, if I run it from command line (php -f test.php), it prints "match" as expected.
But if I run it through web server (apache, http://localhost/test.php), it prints "no match".
I am using PHP 5.3.
Any idea why it behaves differently?
How do I make it work through web server?
thanks.
<?php
function myCallback($matches) {
return $matches[0];
}
$value = 'aaa äää';
$pattern = '/(\bäää)/u';
$value = preg_replace_callback($pattern, 'myCallback', $value, -1, $count);
if ($count > 0) {
echo "match";
} else {
echo 'no match';
}
?>
Try changing default_charset using iniset('default_charset','utf-8').
If it works, it means that CLI and Apache PHP configs have separate php.ini configurations and perhaps this variable is set differently, or maybe based on environment.
You can leave that in as a solution or find an alternative.
Cheers,
Dan
Check your test.php for it to have the correct headers. In PHP you should state:
header('Content-Type: text/html; charset=utf-8');
As in your HTML head:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
As standard it is set to ISO-8895-1 and maybe that is causing the problem. Here you can find some more information about multiple encodings (if utf-8 encoding is not acceptable) and about utf-8 self: http://devlog.info/2008/08/24/php-and-unicode-utf-8/
I am having issues importing a CSV file which contains (french) names with accents in them... when ever they are imported the accent do not display properly example
félix turns into fŽlix
the file is created by hand and then imported into PHP.
I have tried both utf8_encode() and utf8_decode() and nether function will convert the chars so they can be viewed properly.
my question is how can i get this to render properly... convert char-set.. etc
I believe the text is encoded in Cp850 based on other questions i've seen on here. I am using fgetcvs() to get the contents.
Set Header Information before you output as UTF
header('Content-Type: text/html; charset=utf-8');
$log = file_get_contents("log.csv");
echo utf8_encode($log);
Output
félix
Please, try iconv() function
I think this is late answer but may be helpful for those who are still searching for solution. This is just a tweak. Not always recommended .
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=filename.csv');
echo "\xEF\xBB\xBF"; // UTF-8 with BOM
readfile("filename.csv");
exit;
I'm doing this on upload
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir .$target_file)) {
$log = file_get_contents($target_dir .$target_file);
file_put_contents($target_dir .$target_file, utf8_encode($log));
This is my PHP code:
<?php
$result = '';
$str = 'Тугайный соловей';
for ($y=0; $y < strlen($str); $y++) {
$tmp = mb_substr($str, $y, 1);
$result = $result . $tmp;
}
echo 'result = ' . $result;
The output is:
Тугайный Ñоловей
What can I do? I have to put $result into a MySQL database.
What's the encoding of your file? It should be UTF8 too. What's the default charset of your http server? It should be UTF-8 as well.
Encoding only works if:
the file is encoded correctly
the server tells what's the encoding of the delivered file.
When working with databases, you also have to set the right encoding for your DB fields and the way the MySQL client communicates with the server (see mysql_set_charset()). Fields only are not enough because your MySQL client (in this case, PHP) could be set to ISO by default and reinterprets the data. So you end up with UTF8 DB -> ISO client -> injected into UTF8 PHP script. No wonder why it's messed up at the end :-)
How to serve the file with the right charset?
header('Content-type: text/html; charset=utf-8') is one solution
.htaccess file containing AddDefaultCharset UTF-8 is another one
HTML meta content-type might work too but it's always better to send this information using HTTP headers.
PS: you also have to use mb_strlen() because strlen() on UTF8 strings will probably report more than the real length.
If you're going to send a mix of data and don't want to specify utf-8 using a php header, you can add this html to your page:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
I suppose, your code is in windows-1251 encoding since it is Russian :)
convert your string to utf-8:
$str = iconv('windows-1251', 'utf-8', $str);
If your database is UTF-8, it's ok for mysql.
For your echo, if you do it in a web site, put this in the top page:
header('Content-Type: text/html; charset=UTF-8');
Just add this line at the beginning, after the connection with server:
mysqli_set_charset($conn,"utf8");
try this:
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header("Pragma: no-cache");
header("Expires: 0");
//print "$name_field\n$data";
// با این کد درست شد
print chr(255) . chr(254) . mb_convert_encoding("$name_field\n$data", 'UTF-16LE', 'UTF-8');
if you are just using PHP echo with no HTML headers etc., this worked great for me.
$connect = mysqli_connect($host_name, $user_name, $password, $database);
mysqli_set_charset($connect,"utf8");