Convert arrays into UTF-8 ? PHP JSON

前端 未结 7 1873
盖世英雄少女心
盖世英雄少女心 2021-01-03 01:56

i have multidimensional arrays generated by PHP with data from database ,but i have chars like \"č ć š đ ž\" and when i try to output that in json he just returns null , i d

7条回答
  •  不知归路
    2021-01-03 02:34

    $row = utf8_encode( $row );
    convertUtf8ToHtml( $row );
    $ROW_APP_DATA[] = $row;
    
    See function below:
    
    
    // converts a UTF8-string into HTML entities
        //  - $utf8:        the UTF8-string to convert
        //  - $encodeTags:  booloean. TRUE will convert '<' to '<'
        //  - return:       returns the converted HTML-string
        function convertUtf8ToHtml(&$utf8, $encodeTags = false ) 
        {
            if( !is_string( $utf8 ) || empty( $utf8 ))
             { return false; }
            $result = '';
            for ($i = 0; $i < strlen($utf8); $i++) {
                $char = $utf8[$i];
                $ascii = ord($char);
                if ($ascii < 128) {
                    // one-byte character
                    $result .= ($encodeTags) ? htmlentities($char) : $char;
                } else if ($ascii < 192) {
                    // non-utf8 character || not a start byte
                } else if ($ascii < 224) {
                    // two-byte character
                    $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
                    $i++;
                } else if ($ascii < 240) {
                    // three-byte character
                    $ascii1 = ord($utf8[$i+1]);
                    $ascii2 = ord($utf8[$i+2]);
                    $unicode = (15 & $ascii) * 4096 +
                               (63 & $ascii1) * 64 +
                               (63 & $ascii2);
                    $result .= '&#$unicode;';
                    $i += 2;
                } else if ($ascii < 248) {
                    // four-byte character
                    $ascii1 = ord($utf8[$i+1]);
                    $ascii2 = ord($utf8[$i+2]);
                    $ascii3 = ord($utf8[$i+3]);
                    $unicode = (15 & $ascii) * 262144 +
                               (63 & $ascii1) * 4096 +
                               (63 & $ascii2) * 64 +
                               (63 & $ascii3);
                    $result .= '&#$unicode;';
                    $i += 3;
                }
            }
    
            $utf8 = $result;
            return true;
        }
    

提交回复
热议问题