PHP json_encode umlauts

Viewed 225

I'm getting json strings from an HTTP API. The content type is Content-Type: application/json; charset=UTF-8.

I then proceed to write the strings to a file using.

fwrite($fp, json_encode($post));

The strings contain encodings for umlauts as follows.

Au\u00dfenministerium verh\u00e4ngte Reisewarnung f\u00fcr Kroatien in Kraft getreten.

This should be.

Außenministerium verhängte Reisewarnung für Kroatien in Kraft getreten.

How can I encode the strings to write umlauts to files and not their encoding?

I tried the following.

<?php
$string = "Au\u00dfenministerium verh\u00e4ngte Reisewarnung f\u00fcr Kroatien in Kraft getreten.";
$string = utf8_encode($string);
echo $string;

The output of this script still shows the encoding.

1 Answers

That is the default behaviour of the json_encode function, but you can override this by specifying the JSON_UNESCAPED_UNICODE option. So for example:

json_encode("Außenministerium", JSON_UNESCAPED_UNICODE);

And in your code you should do:

fwrite($fp, json_encode($post, JSON_UNESCAPED_UNICODE));

Also check out which other options you can use in the documentation

Related