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?
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.
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.
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.
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 }';
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With