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.

    评论

报告相同问题?