weixin_33736048 2016-04-21 17:44 采纳率: 0%
浏览 15

UTF-8 php-mysqli无法正常工作

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/279170/utf-8-all-the-way-through" dir="ltr">UTF-8 all the way through</a>
                            <span class="question-originals-answer-count">
                                (15 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2019-05-12 11:20:37Z" class="relativetime">12 months ago</span>.</div>
        </div>
    </aside>

I'm using ajax to get my results from my query. The ajax gives the response (sql query executes successfully) but some characters (croatian language) are broken, hence utf-8 doesn't function correctly.

In my php script, I've tried the following:

$con->set_charset('utf8');

OR

$con->query("SET NAMES 'utf8'");

I've also added the following line in the header:

header('Content-Type: text/html; charset=utf-8');

as well as the content type in my client-ajax code:

contentType: "application/json; charset=utf-8"

Still my characters break, I'm not getting utf-8 valid response. In phpMyAdmin I've got the utf8_general_ci collation which I believe is ok.

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33743703 2016-04-22 07:03
    关注

    I have found the answer.

    The second argument (JSON_UNESCAPED_UNICODE) inside the json_encode() function was the problem.

    echo json_encode($myArray,JSON_UNESCAPED_UNICODE);
    

    So along with JSON_UNESCAPED_UNICODE you have to add the following line of code which is ENOUGH.

    $con->set_charset('utf8');
    

    If you switched $con->set_charset('utf8'); to $con->query("SET NAMES 'utf8'"); then it wouldn't work (you'd get a server 500 error).

    The header('Content-Type: text/html; charset=utf-8'); is not required.

    Before you fix your php code you have to make sure that when you run your query against the database in phyMyAdmin or smillar, the collation needs to be utf8 in my case utf8_general_ci.

    Of-course, don't forget the

    dataType: "json"

    in jquery-ajax.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示