Values in UTF-8 being encoded as NULL in JSON

后端 未结 5 2068
鱼传尺愫
鱼传尺愫 2021-02-08 19:39

I have a set of keywords that are passed through via JSON from a DB (encoded UTF-8), some of which may have special characters like é, è, ç, etc. This is used as part of an auto

5条回答
  •  时光取名叫无心
    2021-02-08 20:28

    The reason could be the current client character setting. A simple solution could be to do set the client with mysql_query('SET CHARACTER SET utf8') before running the SELECT query.

    Update (June 2014)

    The mysql extension is deprecated as of PHP 5.5.0. It is now recommended to use mysqli. Also, upon further reading - the above way of setting the client set should be avoided for reasons including security.

    I haven't tested it, but this should be an ok substitute:

    $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
    if (!$mysqli->set_charset('utf8')) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
    } else {
        printf("Current character set: %s\n", $mysqli->character_set_name());
    }
    

    or with the connection parameter :

    $conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
    if (!mysqli_set_charset($conn, "utf8")) {
        # TODO - Error: Unable to set the character set
        exit;
    }
    

提交回复
热议问题