简体   繁体   中英

Save data to JSON File in correct format - PHP

I am currently saving click co-ordinates to a JSON file through the use of the following code:

onmouseup = function(e){
  var Clicks = {};
  Clicks.state = {
    cX: e.clientX,
    cY: e.clientY,
  }
  $.ajax({
    type : "GET",
    url : "PHP/save_json.php",
    data : {
      state : JSON.stringify(Clicks.state)
    }
  });
}

<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>

However with the above code I am saving the coordinates in the following incorrect format:

{"cX":467,"cY":374}{"cX":56,"cY":474}

Can anyone please help me to save the coordinates in a JSON array rather than in seperate JSON entries?

I would like the file to be as follows, were the coordinates are added onto the already existing JSON array within the file:

{ 
   "ID":["1","2"],
   "cX":["467","56"],
   "cY":["374","474"]
}

You need load data to array, add new data and save back to file.

I think you don't need save numbers in strings. These code create new file if not exists.

<?php
// test input data
if(isset($_GET['state']['cX']) && 
   isset($_GET['state']['cY']) && 
   is_numeric($_GET['state']['cX']) && 
   is_numeric($_GET['state']['cY']) ) 
{
    // ok
} else {
   exit('Bad data format');
}

$myFile = __DIR__ . "/JSON/clicks.json";

// step 1, load data from file to array
$array = file_exists($myFile) ? 
    json_decode(file_get_contents($myFile), true) : 
    [];

// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];

// step 3, save array back to file
file_put_contents($myFile, json_encode($array));

Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV

What you need to do is:

  • Open the clicks.json file and read the entire contents.
  • Turn this into an instance of stdClass by using json_decode . This will give you a PHP object that you can modify using normal PHP functions and syntax.
  • Use json_decode on the JSON that you receive from your client.
  • Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX); )
  • Use json_encode to encode $fileJson again.
  • Write it back to the file.

This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.

Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:

[{"cX":467,"cY":374},{"cX":56,"cY":474}]

The PHP code can be written as (illustrated with static input):

$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source  =   json_decode($string, true);

$json_array_target  =   array();
foreach($json_array_source as $key=>$value){
    $json_array_target["ID"][]  =   $key + 1;
    foreach($value as $sub_key => $sub_value){
        $json_array_target[$sub_key][]  =   $sub_value;
    }
}

$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);

If you were to echo $transformed_string; , you'd see:

{"ID":[1,2],"cX":[467,56],"cY":[374,474]}

Which is what will be written to the file.

Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.

$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);

http://php.net/manual/en/function.json-encode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM