douhulao7642 2014-09-29 13:02
浏览 192
已采纳

使用ODBC从MSSQL获取UTF-8

I have problems selecting text from a MSSQL Database. I am connecting through ODBC with the SQL Server Native Client 10.0 driver. The Data is stored in a ntext column with UTF-8 characters and I need to output it correctly with PHP, if you are curious it's a download script. I've tried several tricks and tips like converting the character encoding but none of them really worked.

I have to mention that I am not able to change anything in the database.

<?php
odbc_connect();
odbc_execute();
odbc_fetch_row();
header("Content-type: application/octet-stream");
echo odbc_result(...., 'ntext-column');
  • 写回答

1条回答 默认 最新

  • douliao1911 2014-09-29 16:25
    关注

    Finally I got the solution. You have to cast your column to VARBINARY in the select query. If you have a ntext column you have to cast it to nvarchar first.

    SELECT CAST(CAST(column AS NVARCHAR(MAX)) AS VARBINARY(MAX)) AS column FROM ...

    Then you have to enable the binary mode for odbc and set the expected length of the binary data. Finally you have to convert the binary data from the charset UCS-2LE to UTF-8, then it's done.

    ...
    odbc_execute($query, ...);
    odbc_longreadlen($query, 1000000); // Set the expected length to 1 Megabyte
    odbc_binmode($query, ODBC_BINMODE_RETURN); // Enable binary mode
    ... // Fetch the row
    $data = iconv('UCS-2LE', 'UTF-8', odbc_result($query, 'column'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器