0

I'm trying to be able to write to a json file. I think maybe I missed something because I'm not able to write to the json file and no errors show up.

Here is my code

public function writingToFile($id, $from, $to)
{

    mkdir($this->getStoragePath($id, "/file/$to"));

    foreach(['name', 'area'] as $file){
        copy($this->getStoragePath($id, "/file/$from/$file.json"), $this->getStoragePath($id, "/file/$to/$file.json"));
    }

    $version_file->area = $to;
    $json_file = file_get_contents($this->getStoragePath($id, '/file/$to/area.json'));
    $version_file = json_decode($json_file);


    file_put_contents($this->getStoragePath($id, "/file/$to/area.json"), json_encode($version_file, JSON_PRETTY_PRINT));


}
user3095193
  • 317
  • 2
  • 6
  • 17
  • 1
    Can you indicate what particularly is failing? Does it read the file? Do the files get copied? – Nigel Ren Mar 15 '20 at 08:05
  • @NigelRen - The files do get copied. They just don't get written to. So I'm thinking maybe it's on this line `file_put_contents($this->getStoragePath($id, "/file/$to/area.json"), json_encode($version_file, JSON_PRETTY_PRINT));` but I'm not sure – user3095193 Mar 15 '20 at 08:32
  • Always worth trying to split it out for debugging, so check that `$this->getStoragePath()` is giving you what you would expect, and that the `json_encode()` is doing the same. You can also check the return value from `file_put_contents()` to see what happens there. – Nigel Ren Mar 15 '20 at 08:34
  • @NigelRen - Thank you so much. If it wasn't for your advice, I think I would have gone mad. The issue was that I needed to put double quotes for `$json_file = file_get_contents($this->getStoragePath($id, '/file/$to/area.json'));` instead of single quotes – user3095193 Mar 15 '20 at 08:48

0 Answers0