display system date in php | m.vk.com create english magazine | php post to twitter | jquery themeswitcher
 


 

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;
}

Hope to find it helpful. Your comments are welcomed!

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips