使用PHP从SQL Server检索中文数据?

时间:2015-07-20 06:53:35

标签: php sql-server json

我想使用PHP在SQL Server中检索中文语言数据存储。我尝试使用下面的代码但是它无法正常工作。它刚刚回归????????????

我的代码:

$query = "SELECT                   
               [name]
              ,[venue]                
              FROM tablename
              WHERE id = '2'";

/**********************************************/
//Just for the Purpose of Count Number of Rows
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
/******************************/

#Query the database to get the user details. 
$res = sqlsrv_query($conn, $query, $params, $options);  

$arr = array();
#If no data was returned, check for any SQL errors 
if ($res == false) 
{ 
   echo 'Query not Executed : '.  die(print_r(sqlsrv_errors(), TRUE));
}
else
{       
    while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
    {
        $arr[] = array(
        "name" => $obj['name'],
        "venue" => $obj['venue']
        );
    }
}

header('Content-type: application/json; charset=utf-8');
#Output the JSON data 
echo json_encode($arr);
exit();


sqlsrv_free_stmt($res); // Closes a statement. Frees all resources associated.
sqlsrv_close($conn);    // Closes a connection. Frees all resources associated.

我的数据库表结构:
enter image description here

1 个答案:

答案 0 :(得分:1)

经过深思熟虑之后,我终于找到了解决方案我自己和解决方案只是在连接字符串中添加字符集选项。

例如:

$result = sqlsrv_connect($hostname, array(
        'UID' => $username,
        'PWD' => $password,
        'Database' => $database,
        "CharacterSet" => "UTF-8"      
));

所以只需添加“CharacterSet”=> “UTF-8”

希望它能解决问题。

感谢。