一、封裝2個(gè)函數(shù),讀寫(xiě)文件
/**
* @desc 讀取文件內(nèi)容
* @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 將數(shù)組數(shù)據(jù)寫(xiě)入文本
* @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,
];
//將內(nèi)容寫(xiě)入文件
$writeResult = $this->writeContent($contents, $filename);
if(!$writeResult){
echo '數(shù)據(jù)寫(xiě)入文件失?。?;
}
//讀取文件內(nèi)容
$result = $this->readContent($filename);
/**輸出內(nèi)容:
array (
'name' => '張三',
'sex' => '男',
'age' => 20,
)
*/
var_export($result);exit;
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-782014.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-782014.html
到了這里,關(guān)于php將文本內(nèi)容寫(xiě)入一個(gè)文件(面向過(guò)程寫(xiě)法)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!