2

I am trying to write data in a json file from yii2 framework. It's returning error failed to open stream. My code is given below.

$productjson = json_encode($value);
echo $jsonfile=Yii::$app->view->theme->baseUrl.'/assets/json/aresult.json';
$fp = fopen($jsonfile, 'w+');
fwrite($fp, $productjson);
fclose($fp);
M.Kaisar
  • 63
  • 1
  • 8

2 Answers2

7

That's the right way to specify the path

 $productjson = json_encode($value);
 echo $jsonfile= Yii::getAlias('@webroot/assets/aresult.json');
 $fp = fopen($jsonfile, 'w+');
 fwrite($fp, $productjson);
 fclose($fp);

And yii2 has a class to work with json

gud3
  • 555
  • 3
  • 10
3

Your $jsonfile variable contains the file URL, while it should contain your file's path in the server. Check the predefined aliases.

For example:

$jsonfile=Yii::getAlias('@app').'/assets/json/aresult.json';
gmc
  • 3,910
  • 2
  • 31
  • 44
  • Thanks @gmc for trying to help me. Your example is also working but I am sorry for not to checked as solved. – M.Kaisar Mar 30 '17 at 11:04