【问题标题】:PHP decoding json to xml because of special characters由于特殊字符,PHP将json解码为xml
【发布时间】:2018-06-28 10:02:09
【问题描述】:

我正在尝试将 json 转换为我必须存储在 mysql 数据库中的 xml 字符串。由于 json 中的特殊字符,这不起作用。

正如您在示例代码中看到的那样,我找到了一种在浏览器中查看精细字符串的方法。

<?php
// example response
$json = '{"examples":"„Plötzlich“ los – und (†30) Wird’s H&M"}';

// decode ...
$jsonArray = json_decode($json, true);

// ... to convert it
$xmlData = '<?xml version="1.0" encoding="utf-8"?><item>';
$xmlData .= iconv('UTF-8', 'Windows-1252', $jsonArray['examples']);
$xmlData .= '</item>';

//echo ('without encoding: ' . $jsonArray['examples'] . ' ... without encoding: ' . iconv('UTF-8', 'Windows-1252', $jsonArray['examples']));
echo($xmlData);

/*
 * with the first echo the xml string looks like 
 * <?xml version="1.0" encoding="utf-8"?><item>„Plötzlich“ los – und (†30) Wird’s H&M</item>
 * 
 * without the first echo it looks like 
 * <?xml version="1.0" encoding="utf-8"?><item>�Pl�tzlich� los � und (�30) Wird�s H&M</item><item>„Plötzlich“ los – und (†30) Wird’s H&M</item>
 */
?>

但是尝试将该字符串写入数据库将在第一个 � 处停止。

我的错在哪里?如何保留特殊字符?

【问题讨论】:

  • 听起来您没有将脚本文件正确保存为 为 UTF-8 ...
  • 我将一个新文件保存为 UTF-8,但它也不起作用...... :-(

标签: php json xml


【解决方案1】:

我找到了解决方案……它只是 json_decode 中的一个附加选项:

$jsonArray = json_decode($json, true, JSON_UNESCAPED_UNICODE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多