1

我正在尝试将来自 jquery ajax 调用的 JSON 数组传递给 php 文件,并且在 php 文件中,我正在将接收到的数据写入文件。我的代码:

var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"test@yahoo.com","type":null,"selected":true}],"first_name":"Test"}];
    $.ajax({
    url: 'handler.php',
    type: "POST",
    dataType: 'json',
    data:  { 'json': JSON.stringify(contacts) } ,
    success: function(response){
        alert(response);
    }
});

和php代码:

$json = $_POST['json'];
    $response = json_decode($json);

$file = fopen('test.txt','w+');
    fwrite($file, $response);
    fclose($file);

echo "Done";

它没有将 json 数据写入文件,即文件为空

4

1 回答 1

0

json_decode接受一个 JSON 字符串,并将其解析为一个对象(或关联数组)。由于您想将其写入文件,因此您无需先解析它(将字符串写入文件,而不是对象)。

$json = $_POST['json'];
file_put_contents('text.txt', $json)
于 2013-08-17T06:25:43.070 回答