Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recording a JSON POST to File Using PHP

Tags:

json

php

I'm trying to record data that is being posted to my server to a text file. An example of the data that is being sent to my server is located here:

http://dev.datasift.com/docs/push/sample-output-file-based-connectors

It says on that page:

"For all file-based connectors, the payload is a JSON object containing metadata plus an array containing the JSON objects from your stream."

I have the following PHP at the location I have datasift sending data to:

<?php
$myFile = "testFile.txt";
$phpObj = json_decode($_POST['json']);
file_put_contents($myFile,$phpObj);
echo '{ "success": true }';
?>

I know data is being sent, but nothing is being recorded in my text file. It's just blank every time. I have no idea where to go from here unfortunately. Any ideas?

like image 1000
Learning Avatar asked Jun 05 '13 04:06

Learning


People also ask

How get post JSON in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

How do I push data into a JSON file?

push(newData); To write this new data to our JSON file, we will use fs. writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it.

How can we store form data in JSON file using PHP?

Using PHP scripting we can store a form value in array format. After that will convert the array into JSON data using json_encode() predefined function. Then at last we can move the data to JSON format file. Once all data get validated, we need to add in JSON file.


1 Answers

I think you want to get the raw content of the POST, This works for me with both POST and PUT:

$phpObj = json_decode(file_get_contents("php://input"));

$_POST contains the array from x-www-form-urlencoded content, not json.

Hope that points you in the right direction :)

Edit: @user4035 is right... your also trying to save a php object to a file... This is what i would do:

<?php
$jsonString = file_get_contents("php://input");
$myFile = "testFile.txt";
file_put_contents($myFile,$jsonString);
echo '{ "success": true }';
?>
like image 72
complistic Avatar answered Sep 18 '22 10:09

complistic