Escape JSON Special Characters using PHP

Escape JSON Special Characters using PHP

php > 5.2

$str_valid=json_encode($str);

php versions older that 5.2

/**
 * @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;
}

result

{“message”:”\\”}  =>  {\”message\”:\”\\\\\”}
{\”message\”:\”\\\\\”}

use the json_encode constant JSON_HEX_APOS as the second parameter which will convert all single quotes ‘ to \u0027. :

var t = <?php echo json_encode($data,JSON_HEX_APOS);?>;

Leave a Reply

Your email address will not be published. Required fields are marked *