Home > Backend Development > PHP Problem > How to return json in php

How to return json in php

藏色散人
Release: 2023-03-17 06:18:01
Original
5431 people have browsed it

php返回json的方法:1、在php文件中设置“header('Content-Type:application/json; charset=utf-8');”;2、创建“array('a'=>1,'b'=>2);”;3、通过“exit(json_encode($data));”返回json数据即可。

How to return json in php

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑

PHP如何返回json数据?

php返回json,xml,JSONP等格式的数据

1、返回json数据:

header('Content-Type:application/json; charset=utf-8');
$arr = array('a'=>1,'b'=>2);
exit(json_encode($data));
Copy after login

注意:如果不加header直接输出json_encode的值的话,返回的是字符串不是对象,js那边就需要先eval('('+data+')')转化为对象,再取值。

2、返回xml数据:   

header('Content-Type:text/xml; charset=utf-8');
exit($xml);
Copy after login

3、返回jsonp数据:

$arr = array('a'=>1, 'b'=>2, 'c'=>3);
$json = json_encode($arr);
$callback = $_GET['callback'];
exit($callback."($json)");
Copy after login

// 注意callback是js传过来的参数名称

thinkphp如何返回各种数据:

$this->ajaxReturn (json_encode($arr),'JSON');
$this->ajaxReturn (json_encode($arr),'JSONP');
$this->ajaxReturn (json_encode($arr),'XML');
Copy after login

json_encode有个参数禁止unicode编码

JSON_UNESCAPED_UNICODE

json_encode('中文',JSON_UNESCAPED_UNICODE);
Copy after login

默认中文编码

header('Content-Type:application/json; charset=gbk');

$data = $db->select($sql);
$data = json_encode($data);
$data=preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'gbk', pack('H4', '\\1'))", $data);

exit($data);
Copy after login

长度用count()

$sjson = json_decode($res);  
for($i=0;$i<count($sjson);$i++)
{ 
    echo $sjson[$i];
}
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of How to return json in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template