Search code examples
phpencodingcharacter-encodingarabiciconv

database issue with arabic encoding


I have a wordpress website and for some reason all records values that are in Arabic language change to be like this موقع الطب النÙسي although the database and it's tables collation utf8mb4_unicode_ci.To fix this issue i have decided to make script to select all records from each table and then iconv each value to be for example something like this عنوان باللغة العربية.

Now the problem i have tried everything and it's not working for me

    header('Content-Type: text/html; charset=utf-8');

$sql['host']        = "localhost";
$sql['username']    = "root";
$sql['password']    = "";
$sql['database']    = "nafsynet_database";

$connection = mysqli_connect($sql['host'], $sql['username'], $sql['password'], $sql['database']);

if (!$connection) {
    $out .= "Error: Unable to connect to MySQL." . PHP_EOL;
    $out .= "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    $out .= "Debugging error: " . mysqli_connect_error() . PHP_EOL;

    echo $out;

    die();
}

$sql    = "SELECT * FROM `nfsy_options` WHERE 1 LIMIT 10";
$result = mysqli_query($connection, $sql);
$rows   = mysqli_fetch_all($result,MYSQLI_ASSOC);

foreach($rows as $row) {
    $text =  $row['option_value'];

    echo iconv('windows-1256', 'utf-8',$text);echo'<br>';
}

mysqli_close($connection);

Solution

  • You also need to specify utf8 charset for your database connection, by calling mysqli_set_charset

    $connection = mysqli_connect($sql['host'], $sql['username'], $sql['password'], $sql['database']);
    
    if (!$connection) {
        // ..
    }
    
    mysqli_set_charset($connection, 'utf8');
    
    $sql    = "SELECT * FROM `nfsy_options` WHERE 1 LIMIT 10";