在PHP中接收JSON,并将输入保存为TXT文件


Receive JSON in PHP and save input as TXT file

我是PHP的新手,我想完成以下任务。

接收JSON请求并将结果存储在txt文件中。我发送的JSON请求:

{"first_name":"William"}

我用来接收JSON:的PHP代码

        <?php
$request = file_get_contents('php://input');
$input = json_decode($request);
$firstName = $input;
$text = print_r($firstName,true);
file_put_contents('output.txt', var_export($text, TRUE));

文本文件已创建,但文本文件中没有内容。

使用此代码

if(isset($_POST['input']){
 $input$_POST['input']; 
file_put_contents('output.txt', var_export($input, TRUE));
}

试试这个

更换

$text = print_r($firstName,true);

带有

$text = $input->{'first_name'};

或者使用这个

$firstName =$input->{'first_name'};
$text = print_r($firstName,true);

以下代码适用于

$request = file_get_contents('php://input');
$input = json_decode($request,true);
$firstName = $input['first_name];
$text = print_r($firstName,true);
file_put_contents('output.txt', var_export($text, TRUE));