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

4
  • Oh..... You are right. Commented Nov 21, 2016 at 6:28
  • Try the option 'JSON_ERROR_CTRL_CHAR' Commented Nov 21, 2016 at 6:30
  • 1
    Try this: stackoverflow.com/questions/6606713/… Commented Nov 21, 2016 at 6:31
  • 1
    Just tossing this out there, from the json_encode() documentation page: "All string data must be UTF-8 encoded." That being said, the JSON_UNESCAPED_UNICODE bitmask option sounds promising. Commented Nov 21, 2016 at 6:42

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Your code output: ["hello","180.00 10\u00b5H"]. Notice the µ converted to respective special characters(\u00b5).
@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.
am getting error utf8_encode() expects parameter 1 to be string, array given in line#
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

1 Comment

am getting blank response , maybe because my final big array is multidimensional

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.