zcynine

 

如何用PHP接收JSON格式数据

1.一般来说,我们直接用$_POST $_REQUEST $_GET这样的超全局变量接收就好了

<?php
    $obj_temp=$_POST[\'data\'];
    echo $obj_temp[\'name\'];
?>

2.但是有时候我们希望转换下格式,比如说数组,这个时候我们就要用到json_decode()方法

先来模拟下前端向PHP发送Request的环境

$(document).ready(function(){
    var jsonText =\'{"user":[{"username":"xx","password":"123"}, {"username":"yy","password":"456"}]}\';
    $("#testLink").click(function(){   
        $.post(\'test.php\',{data:jsonText},function(data){
            alert(data);
        });
    });
});

然后我们用test.php来接收这个请求,并且把请求的data解析出来

<?php 
    $arr = json_decode($_POST[\'data\'],true);
    print_r($arr);
?>

json_decode可以将json字符串转化为数组,这样我们就可以逐条读取数据了,解析出来的数组是这样的

Array ( 
    [user] => Array ( 
        [0] => Array ( 
            [username] => xx 
            [password] => 123 
        ) 
        [1] => Array ( 
            [username] => yy 
            [password] => 456 
        ) 
    ) 
) 

 

 

 

如何用PHP返回JSON格式数据

 

下面这句话必不可少。

header(\'Content-type: text/json\');

 

总的来说,我们一般是在PHP中创建数组,然后用json_encode()方法把数组转化成json格式

<?php
    header(\'Content-type: text/json\');
    $fruits = array (
        "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
        "numbers" => array(1, 2, 3, 4, 5, 6),
        "holes"   => array("first", 5 => "second", "third")
    );
    echo json_encode($fruits);
?>

需要注意的是,需要先把数组中的汉字内容进行编码转换,将GBK的编码转换为UTF-8,否则json_code()会将汉字转为NULL。(从utf-8数据库中取出的值不需要进行转化)

形式可参见如下代码

<?php
    while($row = $db->fetch_array($query)){
        $row[\'uname\'] = mb_convert_encoding($row[\'uname\'],\'utf-8\',\'gbk\');
        $row[\'content\'] = mb_convert_encoding($row[\'content\'],\'utf-8\',\'gbk\');
        $com[] = $row;
    }
    echo json_encode($com);
?>

 

分类:

技术点:

相关文章: