user3662974
user3662974

Reputation: 85

php json_encode korean character broken. how to solve this?

In PHP json_encode Korean characters are broken. How it can be solved this?

I used var_dump but I need JSON type.

My web hosting has 5.2 PHP version, so I can't use

print(json_encode($json_output, JSON_UNESCAPED_UNICODE));


while($row=mysqli_fetch_assoc($query)) {
    $json_output[]=$row;
}

print(json_encode($json_output));

bellow is broken character

[
   {
      "name":"chulhoon",
      "description":"\ud558\ud558\ud638\ud638",
      "dob":"\uc548\ub155\ud558\uc138\uc694",
      "county":"\ub9cc\ub098\uc11c",
      "height":"\ubc18\uac00\uc6cc\uc694",
      "spouse":"\ubb50\ub4e4\ud558\uc138\uc694",
      "children":"\uc774\ubbf8\uc9c0\uc55e\uc790\ub9ac",
      "image":"http:\/\/microblogging.wingnity.com\/JSONParsingTutorial\/johnny.jpg"
   }
]

Upvotes: 1

Views: 1463

Answers (2)

user3662974
user3662974

Reputation: 85

function json_encode2($data) {
    switch (gettype($data)) {
        case 'boolean':
            return $data?'true':'false';
        case 'integer':
        case 'double':
            return $data;
        case 'string':
            return '"'.strtr($data, array('\\'=>'\\\\','"'=>'\\"')).'"';
        case 'array':
            $rel = false; // relative array?
            $key = array_keys($data);
            foreach ($key as $v) {
                if (!is_int($v)) {
                    $rel = true;
                    break;
                }
            }

            $arr = array();
            foreach ($data as $k=>$v) {
                $arr[] = ($rel?'"'.strtr($k,array('\\'=>'\\\\','"'=>'\\"')).'":':'').json_encode2($v);             
        }

        return $rel?'{'.join(',', $arr).'}':'['.join(',', $arr).']';
    default:
        return '""';
}

}

this works cool! thank you everybody.

echo json_encode2($data);

json_encode2

{"test":"test data","sample":"sample string","data2":[0,1,2,3,{"beskin":"31"}],"bool":true,"number_data":33282,"pi":3.14}

Upvotes: -1

Stefan Gehrig
Stefan Gehrig

Reputation: 83682

This is not broken. These strange sequences are unicode characters. You can try to use

print(json_encode($json_output, JSON_UNESCAPED_UNICODE));

instead, if you're PHP >= 5.4. That should keep unicode characters in their original form. But that could result in some other problems when storing or transferring the JSON string.

Upvotes: 4

Related Questions