- json_last_error_msg: documentation ( source)
- json_last_error: documentation ( source)
- str_replace: documentation ( source)
- json_encode: documentation ( source)
<?php
function encode($value, int $flags = 0)
{
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| ($flags & 0)
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
$json = json_encode($value, $flags);
if ($error = json_last_error()) {
throw new Exception(json_last_error_msg(), $error);
}
if (PHP_VERSION_ID < 70100) {
$json = str_replace(["\u{2028}", "\u{2029}"], ['\u2028', '\u2029'], $json);
}
return $json;
}
echo encode((object)[1 => 2]);