【问题标题】:Android with php: Saving utf-8 string to MySQLAndroid 与 php:将 utf-8 字符串保存到 MySQL
【发布时间】:2012-09-28 19:35:46
【问题描述】:

我知道我在问一个以前被问过很多次的问题,但我觉得我需要澄清我的问题。

我有一个将 JSON 编码字符串发送到 PHP 脚本的 Android 应用程序。然后,以下代码将数据保存为完整的 JSON 字符串。 (还有其他功能可以将数据正确保存到多个字段,而不仅仅是一个 JSON 字符串)

$json_complete = $_POST['questionnaire'];
$q = json_decode($json_complete, true);

//save complete json string to database
$query_upload = "INSERT INTO questions_json (q_id, json) VALUES('".mysql_real_escape_string($q[qID])."', '$json_complete') ON DUPLICATE KEY UPDATE json = VALUES(json)";
$result = mysql_query($query_upload) or errorReport("Error in query: $query_upload. ".mysql_error());
if (!$result)
    errorReport($result);

问题在于 JSON 字符串中包含的某些文本取自 Android 中的 strings.xml,该字符串以 utf-8 编码。作为 strings.xml 文件中的示例,<item>Can\'t get there</item> 在 MySQL 中保存为“Canu0027t get there”。此外,“批发和零售”另存为“批发 u0026 零售”。

由于 JSON 字符串中的非 utf-8 编码字符,我在 php 中也遇到了 json_decode() 失败。收到以下错误:格式错误的 UTF-8 字符,可能编码不正确。

如何处理所有这些情况?请帮忙。

【问题讨论】:

  • 为什么 json_decode() 在 php 中失败???你得到一个错误的字符串或你有一个错误消息?
  • 即使你保存 Canu0027t get there,当你将显示这个时,例如 var a = "Canu0027t get there";和警报(a);你会看到:无法到达那里

标签: php android utf-8 json


【解决方案1】:

您还必须在查询中使用mysql_real_escape_string() 您的$json_complete,否则您会丢失原始的/uXXXX 编码。

$json_complete = $_POST['questionnaire'];
$q = json_decode($json_complete, true);

//save complete json string to database
$query_upload = "INSERT INTO questions_json (q_id, json) VALUES('".mysql_real_escape_string($q[qID])."', '".mysql_real_escape_string($json_complete)."') ON DUPLICATE KEY UPDATE json = VALUES(json)";
$result = mysql_query($query_upload) or errorReport("Error in query: $query_upload. ".mysql_error());
if (!$result)
    errorReport($result);

【讨论】:

    【解决方案2】:

    一般来说,现在所有的字符串都应该是 UTF-8,因为它可以轻松实现国际化。您应该设置您的 MySQL 数据库,以便将字符串字段存储为 UTF-8 (utf8_general_ci),并且您不会遇到转换问题。

    如果您坚持在您的数据库中使用另一种编码,您可能需要查看mb_check_encoding($string,'UTF-8')mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8')

    【讨论】:

    • 将我的 MySQL 更改为 utf8_general_ci,但没有任何区别。也试过mb_check_encoding和mb_convert_encoding,也没什么区别。仍然将“it's”保存为“itu0027s”
    • 这很奇怪。所以解码的json包含额外的字符,因为php无法正确解码utf-8 json?或者您可能需要更改从 xml 读取这些字符串并嵌入到 json 中的方式。
    【解决方案3】:

    您是否设置了帖子的编码?

        List<NameValuePair> params = ...;
        HttpPost httppost = new HttpPost(hostname);
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    

    【讨论】:

    • 我试过了,但没有任何区别。仍然将“it's”保存为“itu0027s”
    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 2016-05-31
    • 2023-03-18
    • 2023-03-27
    • 2016-03-26
    • 1970-01-01
    • 2012-12-19
    • 2017-05-14
    相关资源
    最近更新 更多