0

How can i do something like this? Does someone know how to get content from another Json file and overwrite another json file with new value. I tried this but no result. Can someone help me with this, i need this its an commission from school.

the two Json files are list.json and listbackup.json. I want a code that can use listbackup.json file to overwrite list.json.

 $backupFile= file_get_contents("listbackup.json");
        $backupFile= json_encode($backupFile, "\n");
        file_put_contents('list.json', $backupFile);
3
  • 2
    just remove the middle line ? reading a file does not decode the json, so no need to encode it again. Commented Nov 27, 2015 at 12:15
  • 1
    I wonder what your real question here is... Obviously you can write something into a file. It is irrelevant what type of data that is to write data. So what happened that made you ask this question? Commented Nov 27, 2015 at 12:19
  • I have two files, one i want to use as backup and one i use to do changes and all that kind of stuff. Soo what i ask is if after the changes are made and saved in the list.json, how can i use the other list to fill this list back to normal as a backup list. Commented Nov 27, 2015 at 12:22

2 Answers 2

2

If the file is already json you dont need to use json_encode.

Make a backup

$listFile = file_get_contents("list.json");
file_put_contents('listbackup.json', $listFile);

Restore a backup

$backupFile = file_get_contents("listbackup.json");
file_put_contents('list.json', $backupFile);
Sign up to request clarification or add additional context in comments.

Comments

1
$backupFile = file_get_contents("listbackup.json");
$backUpJsonDecoded = json_decode( $backupFile );

// do changes
$backupJsonDecoded->option->value = 'different';

$newFileContents = json_encode( $backupJsonDecoded );
file_put_contents( 'list.json, $newFileContents );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.