Sebastian Kopiczko Sebastian Kopiczko - 1 year ago 244
JSON Question

JSON object from messenger chatbot in PHP

I'm using messenger chatbot with script below from Mr Nadeem Manzoor's tutorial

When I receive json object on line 15th:

$input = json_decode(file_get_contents('php://input'), true);

I want to save whole object as a text in .txt file. How is it possible to do? I'll appreciate any help.
There is whole script:


/* validate verify token needed for setting up web hook */
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'codeandpepper') {
echo $_GET['hub_challenge'];
} else {
echo 'Invalid Verify Token';

/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {

$sender = $input['entry'][0]['messaging'][0]['sender']['id']; //sender facebook id
$message = $input['entry'][0]['messaging'][0]['message']['text']; //text that user sent

$url = '';

/*initialize curl*/
$ch = curl_init($url);
/*prepare response*/
$jsonData = '{
"id":"' . $sender . '"
"text":"You said, ' . $message . '"
/* curl setting to send a json post data */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($message)) {
$result = curl_exec($ch); // user will get the message


Answer Source

If you want to save the JSON String, and that would be the simplest and cleanest thing to do then you will have to break this line up and then just file_put_contents() the string to a file name

/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);


/* receive and send messages */
$json_str = file_get_contents('php://input');
file_put_contents('path/to/file.txt', $json_str);
$input = json_decode($json_str, true);

// and off you go as normal
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download