user889030
user889030

Reputation: 4764

php json_encode bug patch

i have data in text file which i load to array rows wise , but recently i have noticed that when "µ" come in data then json_encode retrun blank response ,and when i remove "µ" from data then json_encode function work

i have php version 5.5.3

$dat = array("0"=>"hello","1"=>"world");
echo json_encode($dat);   // work

$data = array("0"=>"hello","1"=>"180.00 10µH");
echo json_encode($data);  // blank response .. 

i searched for json_enocde function on github php page , but its all in C ,

so any idea how to patch this function

Upvotes: 1

Views: 810

Answers (2)

Keyur Mistry
Keyur Mistry

Reputation: 926

Use the following code:

function utf8_converter($array) {
    array_walk_recursive($array, function(&$item, $key) {
        if (!mb_detect_encoding($item, 'utf-8', true)) {
            $item = utf8_encode($item);
        }
    });

    return $array;
}

$data = array("0"=>"hello","1"=>"180.00 10µH");
$data = utf8_converter($data);
echo json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);

Upvotes: 2

Spencer D
Spencer D

Reputation: 3486

Try this:

$dat = array("0"=>"hello","1"=>"world");
echo json_encode($dat);   // work

$data = array("0"=>"hello","1"=>"180.00 10µH");
echo json_encode($data, JSON_UNESCAPED_UNICODE);

Example: https://ideone.com/cYDf8Y

Upvotes: 0

Related Questions