一、封装2个函数,读写文件
/*** @desc 读取文件内容* @param string $filename* @return array*/
private function readContent(string $filename): array
{$text = file_get_contents($filename);if (!$text) {return [];}$result = json_decode($text,true);return $result ?: [];
}/*** @desc 将数组数据写入文本* @param array $contents* @param string $filename* @return bool*/
private function writeContent(array $contents, string $filename)
{$json = json_encode($contents,JSON_UNESCAPED_UNICODE);if (file_put_contents($filename, $json) !== false) {return true;} else {return false;}
}
二、功能使用
$filename = __DIR__ . "/test.txt";//文件路径
$contents = ['name' => '张三','sex' => '男','age' => 20,
];//将内容写入文件
$writeResult = $this->writeContent($contents, $filename);
if(!$writeResult){echo '数据写入文件失败!';
}//读取文件内容
$result = $this->readContent($filename);
/**输出内容:array (
'name' => '张三',
'sex' => '男',
'age' => 20,
)*/
var_export($result);exit;