0

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:

  1. I am not getting anything back when printing out the decoded object($post_data below).
  2. 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.

asked Jun 13, 2015 at 21:53
1

1 Answer 1

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

answered Jun 13, 2015 at 22:09
Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks so much! I tried literally every single option but this is working! Would you mind a follow up question? Can I use '$post_data['lat']' as is if I want to store this parameter in a database? Thanks!!
definitely. Because using $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";

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.