开发者

PHP JSON parsing, only showing one of three parameters

开发者 https://www.devze.com 2023-04-05 19:04 出处:网络
I have a html page that sends a HTTP POST to a php page, and have embedded a JSON object as a parameter. When I try to retrieve the parameters, however, I can only retrieve \"开发者_StackOverflow社区p

I have a html page that sends a HTTP POST to a php page, and have embedded a JSON object as a parameter. When I try to retrieve the parameters, however, I can only retrieve "开发者_StackOverflow社区pass" and nothing else. Am I missing something about parsing JSON in php??

html POST form:

<form method="POST" action="......../username_exist.php" >
<input type="hidden" name="param" value='{"username":"user123","pass":"147852369qwerfdsazxcv","funny":"funny"}' />
<input type="submit" value="Click Me to submit" />
</form>

and the php page:

$param = json_decode($_POST['param']);
$username = $param['username'];
$pass = $param['pass'];
$funny = $param['funny'];
echo $pass;
echo $username;
echo $funny;

give the result of:

147852369qwerfdsazxcv


From what I've read from PHP Docs, calling json_decode without assoc param will return an object, so you need to access its property like $param->pass, $param->username.

Cheers!


This worked for me on my local:

$param = json_decode($_POST['param']);
$username = $param->username;
$pass = $param->pass;
$funny = $param->funny;
echo $pass;
echo $username;
echo $funny;

The difference is that I used the ->, since it is an object, not an array.


Philip is right, you need to add true as a second parameter to json_decode to get an array back.

$param = json_decode( $_POST['param'], true );

..would return the json as an associative array and make the rest of your code work as expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消