从$_POST接收的json中读取关联数组


Read associative array from json received from $_POST

我有一个php文件接收$_GET信息和$_POST信息,对于$_GET的信息没有问题,所以对于$_POST的信息,我接收这个字符串:

[{"channel":"'/meta'/handshake","id":"10","minimumVersion":"1.0","supportedConnectionTypes":["websocket","long-polling"],"version":"1.0"}]

开始和结束。

那么我该怎么读呢?谢谢你的帮助!

您可以使用json_decode`函数

$channels = json_decode(file_get_contents('php://input')); // parse raw post
print_r($channels) // print structure of channels

首先像这个一样解码json数据

$arr = json_decode($_POST,true);

然后像这个一样访问数据

echo $arr[0]['channel']; // output "/meta/handshake"

工作示例http://codepad.viper-7.com/ZeI9n3

试试这个:

$str  = '[{"channel":"'/meta'/handshake","id":"10","minimumVersion":"1.0","supportedConnectionTypes":["websocket","long-polling"],"version":"1.0"}]';

echo "<pre>";
$arra   = json_decode($str,true);
print_r($arra);
/*Uncomment this for your out put*/
//echo "Required : ".echo $arra[0]['channel']; 

输出:

Array
(
    [0] => Array
        (
            [channel] => /meta/handshake
            [id] => 10
            [minimumVersion] => 1.0
            [supportedConnectionTypes] => Array
                (
                    [0] => websocket
                    [1] => long-polling
                )
            [version] => 1.0
        )
)

参考编号:http://php.net/manual/en/function.json-decode.php