How to Escape JSON Special Characters using PHP

JSON is a data format (possible the most) suitable for use with javascript, especially on ajax operations.

Some characters in strings have to be escaped, otherwise json cannot be parsed and an error will occur.

These characters are double quotes (“), backslash (\) and control characters (most inportant in common use is new line character). You don’t have to escape single quotes. For details, see here.

For example: the following string is invalid:

$str='Lorem ipsum "dolor" sit amet,
consectetur \ adipiscing elit.';

and must be converted to

$str="Lorem ipsum \"dolor\" sit amet,\nconsectetur \\ adipiscing elit.";

How?

The ideal way to escape a string with php, before create a json string is json_encode. This requires php > 5.2

$str_valid=json_encode($str);

(remark: json_encode will enclose initial string with double quotes)

php versions older that 5.2

As an alternative (for older versions of php), a function like the following (Source: stackoverflow) could be used:

/**
 * @param $value
 * @return mixed
 */
function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}