1

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

user889030
  • 4,353
  • 3
  • 48
  • 51

2 Answers2

2

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);
Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74
Keyur Mistry
  • 926
  • 6
  • 18
  • Your code output: `["hello","180.00 10\u00b5H"]`. Notice the `µ` converted to respective special characters(`\u00b5`). – Bhavik Shah Nov 21 '16 at 06:41
  • @BhavikShah yes, right. It will do it. But whenever you are converting it back using json_decode it will come back to it's origin form. So don't worry about it. – Keyur Mistry Nov 21 '16 at 06:42
  • am getting error utf8_encode() expects parameter 1 to be string, array given in line# – user889030 Nov 21 '16 at 07:15
0

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

Spencer D
  • 3,376
  • 2
  • 27
  • 43