JSON 来自 PHP 中 Messenger 聊天机器人的对象

JSON object from messenger chatbot in PHP

我正在使用 Messenger 聊天机器人和下面来自 Mr Nadeem Manzoor's tutorial

的脚本

当我在第 15 行收到 json 对象时: $input = json_decode(file_get_contents('php://input'), true); 我想将整个对象保存为 .txt 文件中的文本。怎么可能呢?我将不胜感激任何帮助。 有完整脚本:

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

?>

如果你想保存 JSON 字符串,那将是最简单和最干净的事情,那么你将不得不打破这一行,然后只 file_put_contents() 字符串到文件名

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