0

Possible Duplicate:
Parse Json in php

I am working with an API that sends a POST request to my PHP script when a user performs an action. I can easily log the raw POST data to a file, for example:

$rawPostData = file_get_contents('php://input');
$all = date("F j, Y, g:i a") . " " . $rawPostData . "\r\n";
file_put_contents("Activity.log", $all, FILE_APPEND);

Writes this to the log file:

October 1, 2012, 12:34 pm [{"changed_aspect": "media", "subscription_id": 2421759, "object": "user", "object_id": "931456", "time": 1349120084}]

The only thing I am interested in is the object_id value. How can I access this value in the raw POST data? I've tried a ton and searched a number of forums for a solution. It seems simple enough but I can't seem to get it. Any ideas?

Community
  • 1
  • 1
Kelly Kiernan
  • 355
  • 3
  • 11
  • that looks like valid JSON data. You should be able to just remove everything before the first `[` and then json_decode the rest. – Jonathan Kuhn Oct 01 '12 at 21:37

2 Answers2

0

Your post data is JSON so use json_decode to turn it into an array containing anobject and access the object_id property

$rawPostData = file_get_contents('php://input');
$json = json_decode($rawPostData);
$json = $json[0];
$all = date("F j, Y, g:i a") . " " . $json->object_id. "\r\n";
file_put_contents("Activity.log", $all, FILE_APPEND);
Musa
  • 96,336
  • 17
  • 118
  • 137
  • This was exactly what I was looking for, thank you. The $json = $json[0] was the trick. I was trying to log $json[0]->object_id but that syntax just doesn't work here. – Kelly Kiernan Oct 03 '12 at 15:11
0

The data returned is json:

$data = json_decode(file_get_contents('php://input'));
foreach($data as $obj) {
    echo $obj->object_id;
}
Ska
  • 168
  • 9