I am trying to pass a JSON array from jquery ajax call to a php file and in php file, I am writing the received data to a file. My code :
我试图将JSON数组从jquery ajax调用传递给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);
}
});
And php code :
和PHP代码:
$json = $_POST['json'];
$response = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $response);
fclose($file);
echo "Done";
It is not writing the json data into the file i.e. File is empty
它不是将json数据写入文件,即File为空
1 个解决方案
#1
0
json_decode
takes a JSON string, and parses it into an object (or associative array). Since you want to write it to a file, you don't need to parse it first (one writes strings to files, not objects).
json_decode接受一个JSON字符串,并将其解析为一个对象(或关联数组)。由于您要将其写入文件,因此您无需先解析它(一个将字符串写入文件,而不是对象)。
$json = $_POST['json'];
file_put_contents('text.txt', $json)
#1
0
json_decode
takes a JSON string, and parses it into an object (or associative array). Since you want to write it to a file, you don't need to parse it first (one writes strings to files, not objects).
json_decode接受一个JSON字符串,并将其解析为一个对象(或关联数组)。由于您要将其写入文件,因此您无需先解析它(一个将字符串写入文件,而不是对象)。
$json = $_POST['json'];
file_put_contents('text.txt', $json)