Home  >  Article  >  Backend Development  >  php jsonp单引号转义_PHP

php jsonp单引号转义_PHP

WBOY
WBOYOriginal
2016-05-31 19:27:221068browse

php中jsonp输出时一般用下面的格式:

代码如下:


callbackname('json string');

如果中间的json string中含有单引号,这个输出就是有问题的,调用方一般是无法处理的,所以我们要对单引号进行转义。

如果是用json_encode方式生成可以用下面的方式转义:

代码如下:


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

这里 JSON_HEX_APOS 是php是提供的把单引号换为 \u0027 了。

如果是字符串拼接的,可以用下面的方式:

代码如下:


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

然后再输出。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn