php返回json,xml,JSONP等格式的數據


php返回json,xml,JSONP等格式的數據

返回json數據:

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

注意:如果不加header直接輸出json_encode的值的話,返回的是字符串不是對象,js那邊就需要先eval('('+data+')')轉化為對象,在取值

 

返回xml數據:

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

 

返回jsonp數據:

$arr = array('a'=>1, 'b'=>2, 'c'=>3);
$json = json_encode($arr);
$callback = $_GET['callback'];
exit($callback."($json)");
//注意callback是js傳過來的參數名稱

 

順便說下thinkphp如何返回各種數據:

$this->ajaxReturn (json_encode($arr),'JSON');

$this->ajaxReturn (json_encode($arr),'JSONP');

$this->ajaxReturn (json_encode($arr),'XML');

 

json_encode有個參數禁止unicode編碼

JSON_UNESCAPED_UNICODE

json_encode('中文',JSON_UNESCAPED_UNICODE);

 

默認中文編碼

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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM