PHP noob here. I am building an iPhone app that is sending JSON blobs to a web server. On the server side I am receiving the JSON and trying to access the 3 fields that the object contains.
Two weird things are happening to me that I could not figure out how to fix:
- I am not getting anything back when printing out the decoded object($post_data below).
- I am actually able to print the full object back in Xcode when printing the object without decoding ($content below) but have no idea how to access the various fields in the object.
My PHP code:
$con = mysql_connect("127.0.0.1","root", "") or die('Could not connect: ' . mysql_error());
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
echo $content; --> prints the object properly
echo $post_data; --> does not print anything
echo $content->lat; --> does not print anything
My JSON object:
{
"lat" : 37.33233141,
"long" : -122.0312186,
"speed" : 0
}
Any help would be greatly appreciated.
-
possible duplicate of PHP json_decode return empty arrayβ.εηοιτ.βε– β.εηοιτ.βε2015年06月13日 22:02:30 +00:00Commented Jun 13, 2015 at 22:02
1 Answer 1
it's because json_decode($content, true) is returning an array, which has problems displaying if you echo the container.
Try doing echo $post_data['lat'];
you can also try using print_r($post_data); to have it output the actual contents of the variable so you can see if something isn't working properly
2 Comments
$post_data['lat'] will essentially replace the variable with it's contents in place. So you could be doing something like "UPDATE TABLE current_location SET lat = '".$post_data['lat']."', long = '".$post_data['long']."' WHERE current_user = '".$user_id."' LIMIT 1";