Getting data with UTF-8 charset from MSSQL server using PHP FreeTDS extension

前端 未结 8 921
暖寄归人
暖寄归人 2020-11-28 09:28

I can\'t seem to get data from MSSQL encoded as UTF-8 using FreeTDS extension.

Connecting:

ini_set(\'mssql.charset\', \'UTF-8\');
$this->_resource         


        
相关标签:
8条回答
  • 2020-11-28 09:51

    MSSQL and UTF-8 are quite a pain in the ... sometimes. I had to convert it manually. The problem: MSSQL doesn't actually know and support UTF-8.

    Convert from database value to UTF-8:

    mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8' ? $value : mb_convert_encoding($value, 'UTF-8');
    

    Converting from UTF-8 to database value:

    mb_convert_encoding($value, 'UCS-2LE', mb_detect_encoding($value, mb_detect_order(), true));
    

    Fortunately I was using Doctrine so all I had was to create a custom StringType implementation.

    0 讨论(0)
  • 2020-11-28 10:00

    I had this problem and it solved by adding this line to my php script before connecting to MSSQL Server:

    ini_set('mssql.charset', 'UTF-8');
    
    0 讨论(0)
  • 2020-11-28 10:03

    If you use freeTDS, you should change below lines on /etc/freetds/freetds.conf:

    [global]
    # TDS protocol version
    tds version = 4.2
    

    To this:

    [global]
    # TDS protocol version
    tds version = 8.0
    ;tds version = 4.2
    

    and finally add this line:

    # set charset
    client charset = UTF-8
    

    ** clinet charset is in global [scope]

    In your queries, you should use N character. like this:

    $query = "INSERT INTO dbo.SMSOutbox (StationID, Dest, Text) VALUES ";
       $query .= '(';
       $query .= "'" . $this->stationId . "', ";
       $query .= "'" . $this->destination . "', ";
       $query .= "N'" . $this->text . "'";
       $query .= ')';
    
    0 讨论(0)
  • 2020-11-28 10:07

    You can also solve this issue by adding CharacterSet UTF-8 in the $connectionInfo before connecting to the DB.

    $serverName = "MyServer";
    $connectionInfo = array( "Database"=>"AdventureWorks", "CharacterSet" => "UTF-8");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
    

    Worked fine NO additional encoding needed.

    0 讨论(0)
  • 2020-11-28 10:07

    I used same as above but windows 1250, so:

    $query = $this->db->query($sql);
    $result = $query->fetchAll(PDO::FETCH_OBJ);
    foreach ($result as $row) {
        foreach (get_object_vars($row) as $key => $value) {
        $row->$key = (mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8') 
                ? $value : iconv('windows-1250', 'utf-8', $value);
        }
        $results[] = $row;
    }
    

    And then it worked, but I use polish characters

    0 讨论(0)
  • 2020-11-28 10:10

    You should change your TDS version based on what version of SQL server your using. Check out the installation guide for details.

    http://www.freetds.org/userguide/choosingtdsprotocol.htm

    0 讨论(0)
提交回复
热议问题