SoFunction
Updated on 2025-03-01

php jsonp single quote escape

When outputting jsonp in php, the following format is generally used:

Copy the codeThe code is as follows:

callbackname('json string');

If the json string in the middle contains single quotes, this output is problematic and the caller generally cannot handle it, so we need to escape the single quotes.

If you are generating using json_encode, you can escape it in the following way:

Copy the codeThe code is as follows:

$ret = json_encode($result, JSON_HEX_APOS);
header('Content-Type: text/javascript; charset=utf-8');
echo $callback . '(\'' . $ret . '\');';

Here JSON_HEX_APOS is provided by php to change single quotes to \u0027.

If it is string splicing, you can use the following method:

Copy the codeThe code is as follows:

$jsonData = preg_replace('/\'/', '\u0027', $jsonData);

Then output it again.