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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么