Search code examples
phputf-8sqlsrv

PHP - Fetching UTF-8 data from sqlsrv database


I'm Trying to fetch some data from sql server database and print in json , but some of the data in database is in UTF-8 (Arabic) . I searched the web and tried many solutions , but none of them worked for me , any help would be appreciated . Here is my code :

<?php

$serverName = "127.0.0.1"; //serverName\instanceName
$connectionInfo = array( "Database"=>"filmnak_com_", "CharacterSet" => "UTF-8", "UID"=>"filmnak", "PWD"=>"G5j^wk44");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$sql = "SELECT CAST(ID AS INT) AS ID, CAST(Film AS TEXT) AS Film ,CAST(Name AS TEXT) Name FROM dbo.Movies";

$result = sqlsrv_query( $conn, $sql);
if( $result === false ) {
     die( print_r( sqlsrv_errors(), true));
}

    // looping through all results
    // products node
    $response["Info"] = array();
  while ($row = sqlsrv_fetch_array($result)) {
        // temp user array
        $Info = array();
        $Info["ID"] = $row["ID"] ;
        $Info["Film"] = $row["Film"];

      $Info["Name"] = utf8_decode($row["Name"]);

    echo $row["Name"];
        // push single product into final response array
        array_push($response["Info"], $Info);
    }


echo json_encode($response , JSON_UNESCAPED_UNICODE);

sqlsrv_free_stmt($result);


?>

the result in browser :

???? ????1+1?????{"Info":[{"ID":8,"Film":"8O9","Name":"???? ????"},{"ID":9,"Film":"9O3","Name":"1+1"},{"ID":10,"Film":"10O5","Name":"?????"}]}

Solution

  • Set the database collation to utf8_general_ci