Sebastian Kopiczko Sebastian Kopiczko - 4 months ago 60
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:

<?php

/* 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'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}

/* 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 = 'https://graph.facebook.com/v2.6/me/messages?access_token=EAAQyP47lxSQBAPQSXyHhQ7y0d0MTQgTn4xaFEDEu5yrc4qo4t0FWbHZAfT7TFQq3HYZCUGVcTPZAaN2ZBNrUShl4Hr5qQd8cqBu0mfB0Al7NZAWjIjQC9UqXQLU5E9IsZBaQDIXglMcEBqNUyiidGJWRPPfvCmtg4vy2UgUhU8SQZDZD';

/*initialize curl*/
$ch = curl_init($url);
/*prepare response*/
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"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

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);

Into

/* 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