How to properly escape JavaScript (JSON) strings in PHP scripts

This is a small script I wrote back in 2007. It has very few improvements since then, and it has proved to be a life saver over and over again.

There are several special characters usually escaped with back slashes, like the quote, double-quote, control characters \b \t \n \f \r and of course the back-slash itself. But this little script goes one step beyond that, it also escapes the inequality symbols < > which have a special meaning in HTML and they may cause problems if left unescaped.

So here it is, enjoy!

if (!function_exists('json_esc')) {
    function json_esc($input, $esc_html = true) {
        $result = '';
        if (!is_string($input)) {
            $input = (string) $input;
        }

        $conv = array("\x08" => '\\b', "\t" => '\\t', "\n" => '\\n', "\f" => '\\f', "\r" => '\\r', '"' => '\\"', "'" => "\\'", '\\' => '\\\\');
        if ($esc_html) {
            $conv['<'] = '\\u003C';
            $conv['>'] = '\\u003E';
        }

        for ($i = 0, $len = strlen($input); $i < $len; $i++) {
            if (isset($conv[$input[$i]])) {
                $result .= $conv[$input[$i]];
            }
            else if ($input[$i] < ' ') {
                $result .= sprintf('\\u%04x', ord($input[$i]));
            }
            else {
                $result .= $input[$i];
            }
        }

        return $result;
    }
}

Example 1

echo json_esc('This is a "JSON" escaped string');

// outputs: This is a valid \"JSON\" escaped string

Example 2

echo 'if (error) alert("' . json_esc("Error: You've done it again.\tI told you to use a serious editor and not C:\\Program Files\\Windows\\notepad.exe") . '")';

// outputs: if (error) alert("Error: You\'ve done it again.\tI told you to use a serious editor and not C:\\Program Files\\Windows\\notepad.exe")