在现有文件中写入数据 Yii2 框架

Write data in existing file Yii2 framework

我正在尝试从 yii2 框架向 json 文件写入数据。它返回错误无法打开流。我的代码如下。

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

您的 $jsonfile 变量包含文件 URL,而它应该包含您的文件在服务器中的路径。检查 predefined aliases.

例如:

$jsonfile=Yii::getAlias('@app').'/assets/json/aresult.json';

这是指定路径的正确方法

 $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