Reputation: 1344
I am new to cakephp. I am trying to save json output as a file in webroot. I would also like read the file into a array.
I know we could output array as json object using json_encode($array). But I am stuck creating and reading json files into an array.
I appreciate any help.
Upvotes: 3
Views: 12646
Reputation: 12577
NOTE: This code belongs within a method in your Model or Controller.
Though cetver's answer is technically correct it's not very "cakey".
For CakePHP specifically I would do the following:
$json = '{"key":"value"}';
$json2 = json_encode(array("a" => 1, "b" => 2));
$path = APP . '[YOUR FOLDER NAME]' . DS . 'json';
$path2 = APP . '[YOUR FOLDER NAME]' . DS . 'json2';
$jsonFromFile;
$json2FromFile;
//write
if(!file_exists($path))
file_put_contents($path, $json);
if(!file_exists($path2))
file_put_contents($path2, $json2);
//read
if(!file_exists($path))
$jsonFromFile = file_get_contents($path, true);
if(!file_exists($path2))
$json2FromFile = file_get_contents($path2, true);
Explanation:
Happy coding.
Upvotes: 3
Reputation: 11829
//write
$json = '{"key":"value"}';
$file = new File('/path/to/file', true);
$file->write($json);
//read
$file = new File('/path/to/file');
$json = $file->read(true, 'r');
$json2array = json_decode($json);
Upvotes: 9