Skip to content
Advertisement

Accessing JSON fields using PHP

I’m setting up a webhook handler that receives a POST. Since I’m not storing the data in a database for this, I’m just having the data print to a text file to see what everything is, using

file_put_contents(dirname(__FILE__)."/response.txt", $test_file, FILE_APPEND);

$_POST[‘data_json’]; returns the following object

{ “time_submitted”:[ “11:47 PM UTC” ], “page_uuid”:[ “657773c0-596b-4cad-b2f6-7e1e197f4df4” ], “phone_number”:[ “3335553344” ], “estimated_move_date”:[ “09/29/2020” ], “email”:[ “toweltest@test.com” ], “page_name”:[ “Test Page” ], “utm_adgroup”:[ “” ], “date_submitted”:[ “2020-09-16” ], “name”:[ “toweltest” ], “source”:[ “AdWords” ], “utm_campaign”:[ “” ], “ip_address”:[ “33.333.333.333” ], “page_url”:[ “http://testurl.com/” ], “utm_term”:[ “” ], “variant”:[ “a” ] }

So I set $_POST[‘data_json’] to a variable

$test_file = $_POST['data_json'];

and I try to print $test_file->email to the file, but nothing prints.

$email = $test_file->email;
file_put_contents(dirname(__FILE__)."/response.txt", $email, FILE_APPEND);

I’ve been encoding and decoding and trying to figure out what’s wrong with my format. Any advice?

Advertisement

Answer

Try this

if your post data is $test_file = $_POST['data_json'];

$data = json_decode($test_file);
$email = $data->email;
file_put_contents(dirname(__FILE__)."/response.txt", $email, FILE_APPEND);

If you still see the issue, check for directory permissions.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement