Learning
Learning

Reputation: 1191

Recording a JSON POST to File Using 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?

Upvotes: 6

Views: 17105

Answers (4)

Niroshan
Niroshan

Reputation: 408

I try this method and it works success. So, I share this here.

Source PHP save POST data to file

web_folder/index.php

<?php
   $responseBody = file_get_contents('php://input');
   $json = json_decode($responseBody);
   //return data
   echo json_encode($json);
   //Save in json file
   if($json){
     $fp = fopen('results_'.time().'.json', 'w');
     fwrite($fp, json_encode($json));
     fclose($fp);
   }
?>

and run the below code in the terminal for testing, it will create a JSON file with the POST request in the same folder. (Here I used localhost) or you can test using Postman.

curl -i -X PUT -d '{"name":"codehref"}' http://localhost:8888/web_folder/index.php

Upvotes: 2

Bastan
Bastan

Reputation: 1029

To bypass the problem I used JSON.stringify.

'formSave' : function(project){
    var s = {
        "name": project.name,
        "data": JSON.stringify(project.data)
    };

    $.post("sdcform/formSave/" + project.name, s);
}

The 'project' object contains the keys 'name' and 'data' and I only wanted to stringify the data part of it.

This way on the server I can do

$data = isset($_POST['data']) ? json_decode($_POST['data']): new \stdClass();
file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));

I could store it directly to the file and save both conversion but I wanted to prettyfy it!

Note: Yes I know! Do not access $_POST directly.

Upvotes: 0

complistic
complistic

Reputation: 2710

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 }';
?>

Upvotes: 8

user4035
user4035

Reputation: 23739

You are trying to save an object, using file_put_contents. While data parameter this function "Can be either a string, an array or a stream resource"

http://php.net/manual/en/function.file-put-contents.php

Look at this example:

<?php
$json = '
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
';

$phpObj = json_decode($json);
var_dump($phpObj);
$myFile = "testFile.txt";
file_put_contents($myFile, $phpObj);
?>

It parses json correctly, but doesn't save anything as well, because php doesn't know, how to serialize $phpObj object.

You need to save raw JSON string:

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

Then you can read the file and parse it if necessary.

Upvotes: 2

Related Questions