将字符串数据写入文件(如果已经存在则覆盖,如果不存在则创建新的)


Writing String Data to a file (Overwrite if already exists and create new if not exists)

我想写一个字符串变量的内容比如$data

插入到名为data.xml的文件中文件夹位置将根据$appId变量

的内容而变化。比如我想在 中写入file
  files_dir/$appId/data.xml

此外,如果该文件已经存在,我想重写,否则我想创建文件夹然后创建文件data.xml

以"w"模式打开文件。如果文件不存在,将尝试创建文件,否则将文件截断为零长度。

$handle = fopen("files_dir/$appId/data.xml", "w");

只允许书写;放置文件文件开头的指针并将文件截断为零长度。如果该文件不存在,请尝试创建它。

你可以检查目录是否存在

if (!is_dir("files_dir/$appId")) mkdir("files_dir/$appId",0777);
$handle = fopen("files_dir/$appId/data.xml", "w");

给出目录和文件的完整路径

您可以使用file_put_contents()写入文件:http://php.net/manual/en/function.file-get-contents.php

您可以使用mkdir()创建文件夹部分:http://php.net/manual/en/function.mkdir.php