2

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.

3
  • Do you have the html tag <meta charset="utf-8"> on the page? Commented Aug 19, 2020 at 15:10
  • I'm not using html. My code is a php script. The full code is here github.com/michaelhochleitner/php_utf8/blob/master/… . Commented Aug 19, 2020 at 15:21
  • Stop using utf8_encode(), it's a terribly-named function that doesn't do what you think it does. It's a forced conversion that doesn't detect or care about the input encoding and will corrupt your data more often than not. Same goes for utf8_decode(). Commented Aug 19, 2020 at 17:01

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.