Mansa
Mansa

Reputation: 2325

Generate json file from PHP trouble special characters

I have a special issue. I am trying to generate a json file to use as my translation file in side Unity3D.

I am doing it like this:

$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;

It actually does the job correct, but... When opening the file in sublimeText I see some weird insert just before special characters like the danish "æ ø å".

enter image description here

Can anyone explain what this is and if I should be concerned? And best of all... How do I get around this.

Any help is appreciated :-)

Upvotes: 1

Views: 55

Answers (2)

aghidini
aghidini

Reputation: 3010

While you can certainly generate JSON by-hand I advise to instead using the built-in json_encode php function (see docs). That function will take care of eventual characters that must be escaped like quotes.

Instead of generating directly the json string you generate an object representation and then convert it to string:

$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;

Upvotes: 2

Fky
Fky

Reputation: 2173

Try to change :

$jsonString = mb_convert_encoding($jsonString,'UTF-8',mb_detect_encoding($jsonString));

and add header

header('Content-type: text/plain; charset=utf-8');

Upvotes: 0

Related Questions