我有一个特殊问题。我正在尝试生成一个json文件,用作Unity3D中的翻译文件。
我这样做:
$lang = $_GET["lang"];
header('Content-disposition: attachment; filename=da.json');
header('Content-type: text/plain');
$jsonString = "{\n";
$result = mysqli_query($con,"SELECT * FROM ReloadedSnippets ORDER BY id");
while ($row = mysqli_fetch_assoc($result)){
$snippetId = $row['id'];
$result1 = mysqli_query($con,"SELECT * FROM ReloadedTranslations WHERE fk_snipId=$snippetId AND lang='$lang'");
$row1 = mysqli_fetch_assoc($result1);
$string1 = $row1["translation"];
$string1 = mysqli_real_escape_string($con,$string1);
$jsonString .= " ";
$jsonString .= '"'.$row['snippet'].'": "'.$string1.'",';
$jsonString .= "\n";
}
$jsonString .= '}';
$jsonString = mb_convert_encoding($jsonString,'utf-8','iso-8859-1');
echo $jsonString;
它实际上正确地完成了工作,但是...当在sublimeText中打开文件时,我看到一些奇怪的插入,就在丹麦语“æøå”之类的特殊字符之前。
任何人都可以解释这是什么以及我是否应该关注?最重要的是......我如何解决这个问题。
感谢任何帮助: - )
答案 0 :(得分:2)
虽然您当然可以手动生成JSON,但我建议使用内置的json_encode
php函数(请参阅docs)。该函数将处理必须像引号一样进行转义的最终字符。
不是直接生成json字符串而是生成对象表示,然后将其转换为字符串:
$jsonData = [];
$result = mysqli_query($con, "SELECT * FROM ReloadedSnippets ORDER BY id");
while ($row = mysqli_fetch_assoc($result)) {
$snippetId = $row['id'];
$result1 = mysqli_query($con,"SELECT * FROM ReloadedTranslations WHERE fk_snipId=$snippetId AND lang='$lang'");
$row1 = mysqli_fetch_assoc($result1);
$string1 = $row1["translation"];
$string1 = mysqli_real_escape_string($con,$string1);
$jsonData[$row['snippet']] = $string1;
}
$jsonString = json_encode($jsonData);
echo $jsonString;
答案 1 :(得分:0)
尝试改变:
$jsonString = mb_convert_encoding($jsonString,'UTF-8',mb_detect_encoding($jsonString));
并添加标题
header('Content-type: text/plain; charset=utf-8');