7

When I use json_encode to encode my multi lingual strings , It also changes special characters.What should I do to keep them same .

For example

<?
echo json_encode(array('şüğçö'));

It returns something like ["\u015f\u00fc\u011f\u00e7\u00f6"]

But I want ["şüğçö"]

2

7 Answers 7

8

try it:

<?
echo json_encode(array('şüğçö'), JSON_UNESCAPED_UNICODE);
Sign up to request clarification or add additional context in comments.

Comments

2

In JSON any character in strings may be represented by a Unicode escape sequence. Thus "\u015f\u00fc\u011f\u00e7\u00f6" is semantically equal to "şüğçö".

Although those character can also be used plain, json_encode probably prefers the Unicode escape sequences to avoid character encoding issues.

Comments

2

PHP 5.4 adds the option JSON_UNESCAPED_UNICODE, which does what you want. Note that json_encode always outputs UTF-8.

Comments

2
  • You shouldn't want this
  • It's definitely possible, even without PHP 5.4.

First, use json_encode() to encode the string and save it in a variable.

Then simply use preg_replace() to replace all \uxxxx with unicode again.

1 Comment

Wait, did I just reply to a question that's more than a year old? :-/
1

json_encode() does not provide any options for choosing the charset the encoding is in in versions prior to 5.4.

2 Comments

@Tom: Is that why you downvoted an answer that was accurate when it was written?
Haha, I just realized I did that. I'm sorry - vote removed. I have no idea why I even viewed this question.
0
<?php

print_r(json_decode(json_encode(array('şüğçö'))));

/*
Array
(   
    [0] => şüğçö
)
*/

So do you really need to keep these characters unescaped in the JSON?

3 Comments

yes because I pass it to HTML via ajax request , and I can not see special characters
@Oguz: Ajax (e.g. asynchronous requests via JavaScript) do not depend on JSON.
Then you're doing something else wrong - Ajax will definitely interpret the \u00e7 characters just fine.
0

Json_encode charset solution for PHP 5.3.3

As JSON_UNESCAPED_UNICODE is not working in PHP 5.3.3 so we have used this method and it is working.

$data = array(
        'text' => 'Päiväkampanjat'
);
$json_encode = json_encode($data);
var_dump($json_encode); // text: "P\u00e4iv\u00e4kampanjat"

$unescaped_data = preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
    return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
}, $json_encode);

var_dump($unescaped); // text is unescaped -> Päiväkampanjat

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.