N
N
Ninja Mate2016-12-06 16:38:50
PHP
Ninja Mate, 2016-12-06 16:38:50

How to solve the problem with storing special characters in MySQL and json_encode for JS?

There is a database with Collation utf8_general_ci (I tried utf8mb4_unicode_ci), we get requests from it and after json_encode we send it to JS

$success = $mysqli->query($query)
        or die ('cannot select activities');

        $myArray=array();
        while($row = $success->fetch_assoc())
        {
            array_push($myArray,$row);
        }
        printf(json_encode($myArray));

If you save a line with such characters to the database
[email protected]#$%^&
then after the json_encode command we get an empty line
. I found similar problems and tried:
json_encode($myArray, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)

I tried to pass through this function, all values ​​turn into null
function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            utf8_encode_deep($input->$var);
        }
    }
}

And so I tried
...
        $myArray=array();
        while($row = $success->fetch_assoc())
        {
            array_push($myArray,$row);
        }

        printf(json_encode(to_utf8($myArray)));

        /* close connection */
        $mysqli->close();

        exit();
    }
}

function to_utf8($in)
{
    if (is_array($in)) {
        foreach ($in as $key => $value) {
            $out[to_utf8($key)] = to_utf8($value);
        }
    } elseif(is_string($in)) {
        if(mb_detect_encoding($in) != "UTF-8")
            return utf8_encode($in);
        else
            return $in;
    } else {
        return $in;
    }
    return $out;
}

How to solve a similar problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2016-12-06
@victorzadorozhnyy

base64_encode, base64_decode

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question