BackTrack57
BackTrack57

Reputation: 395

Convert accents from MySQL to no accent in a web page using PHP

I'm currently stuck trying to convert names like "Kévin" into "Kevin" then "KEVIN".

Current database is set to Latin1_swedish_ci. It does not work if the name comes from MySQL and I don't know why. I've already tryed to change latin1 to utf8_general_ci and nothing change.

The name Kévin is writed as "Kévin" into MySQL.

Fonction in use:

function strToNoAccent($var) {
    $var = str_replace(
    array(
    'à', 'â', 'ä', 'á', 'ã', 'å',
    'î', 'ï', 'ì', 'í', 
    'ô', 'ö', 'ò', 'ó', 'õ', 'ø', 
    'ù', 'û', 'ü', 'ú', 
    'é', 'è', 'ê', 'ë', 
    'ç', 'ÿ', 'ñ',
    'À', 'Â', 'Ä', 'Á', 'Ã', 'Å',
    'Î', 'Ï', 'Ì', 'Í', 
    'Ô', 'Ö', 'Ò', 'Ó', 'Õ', 'Ø', 
    'Ù', 'Û', 'Ü', 'Ú', 
    'É', 'È', 'Ê', 'Ë', 
    'Ç', 'Ÿ', 'Ñ', 
    ),
    array(
    'a', 'a', 'a', 'a', 'a', 'a', 
    'i', 'i', 'i', 'i', 
    'o', 'o', 'o', 'o', 'o', 'o', 
    'u', 'u', 'u', 'u', 
    'e', 'e', 'e', 'e', 
    'c', 'y', 'n', 
    'A', 'A', 'A', 'A', 'A', 'A', 
    'I', 'I', 'I', 'I', 
    'O', 'O', 'O', 'O', 'O', 'O', 
    'U', 'U', 'U', 'U', 
    'E', 'E', 'E', 'E', 
    'C', 'Y', 'N', 
    ),$var);
    return $var;
}

Code working:

$name = "Kévin";
$name = strToNoAccent($name);
$name = strtoupper($name);
echo $name; // Result is KEVIN

Code not working for unknow reason:

$chresult=mysql_query("SELECT * FROM personnel");

$y=0;
        while ($y < mysql_num_rows($chresult)) {
            $name = mysql_result($chresult, $y, 'name');

            $name = strToNoAccent($name);
            $name = strtoupper($name);
            echo $name; // Result is KÉVIN

$y++;
}

Upvotes: 0

Views: 355

Answers (2)

scandel
scandel

Reputation: 1822

Looks like an encoding problem. Have you tried something with iconv ? Like :

$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);

Look at : https://stackoverflow.com/a/3542748/2761700 & How do I remove accents from characters in a PHP string?

UPDATE: also use utf8_encode. Complete code :

$chresult=mysql_query("SELECT * FROM personnel");
$y=0;
while ($y < mysql_num_rows($chresult)) {
    $name = utf8_encode(mysql_result($chresult, $y, 'name'));
    $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
    $name = strtoupper($name);
    echo $name;
    $y++;
}

Upvotes: 1

Tej Patil
Tej Patil

Reputation: 115

Tried to replicate your issue. But found the code is working absolutely fine without any of the issue

enter image description here

here is your code :

Function example demo : " . $name; $con = mysql_connect("localhost","root",""); $db= mysql_select_db("latin",$con); $chresult=mysql_query("SELECT * FROM personnel"); $y=0; while ($y Before conversion : " . $name; $name = strToNoAccent($name); $name = strtoupper($name); echo " After conversion : " .$name; // Result is KÉVIN $y++; } ?>

Upvotes: 0

Related Questions