Josh Randall
Josh Randall

Reputation: 1344

Cakephp read and write json files.

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

Answers (2)

pim
pim

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:

  • $json is a standard pre-written JSON string, no confusion here
  • $json2 shows you an example of how you can encode and array (or object) into a json string for your storage purposes
  • $path utilizes some CakePHP constants. "APP" which gives you a resolvable path to your app folder & "DS" which serves as a system-safe directory separator
  • We then check to make sure our files don't exist, at which point we use the method "file_put_contents" to write our files.

Happy coding.

Upvotes: 3

cetver
cetver

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

Related Questions