Some special characters converted to '_' when saved in JSON format, PHP

时间:2018-08-22 13:45:21

标签: javascript php json ajax

I have a JSON object (passed from front-end by JavaScript and Ajax) in this format:

[{ "telephone": "+381-01-33-33-333", "email": "test@test.com"}]

But when saved as JSON file on server by PHP, all the dots('.') and pluses('+') become underscore sign('_'), like this:

[{ "telephone": "_381-01-33-33-333", "email": "test@test_com"}]

This is my PHP code:

<?php
// Accessing users data sent from frontend
$user = (array) json_decode(key($_POST));

add_data('users', $user);   

function add_data($filename, $data) {

    // Declaring users json file path
    $json_file = '../data/' . $filename . '.json';
    $inp = file_get_contents($json_file);

    // If json file is empty add status data else append status data to existing array
    if($inp == '') {
        $tempArray[] = $data;
    } else {
        $tempArray = (array) json_decode($inp);
        array_push($tempArray, $data);
    }
    // Convert array to json data and write it to users json file
    $jsonData = json_encode($tempArray);
    file_put_contents($json_file, $jsonData);
}
?>

So far, I've checked the contents of JSON on front-end, and it is OK. I also tried to manipulate encoding, but without success.

1 个答案:

答案 0 :(得分:1)

$ _ POST似乎无法正确接收JSON,因此我进行了更改:

$user = (array) json_decode(key($_POST));

$user = json_decode(file_get_contents("php://input"));

在PHP中,我还必须在前端的ajax请求中添加内容类型

$.ajax({
  type: "POST",
  url: "php/add_user.php",
  async: false,
  data: JSON.stringify(user),
  contentType: "application/json; charset=utf-8"
})