使用PHP读写文件时,使用了
WordPress
中推荐的文件操作方法
WordPress建议使用名为WP_FileSystem的文件操作对象来操作文件。
使用WP_FileSystem的过程
这次,我将使用get_contents方法和put_contents方法编写如何读写文件的方法。
PHP标准函数和WP_FileSystem,每个
如何编写
实际上,我将描述如何分别使用PHP标准函数和WP_FileSystem操作文件。
读取文件
使用file_get_countents函数读取文件时
1 2 3 | <?php $path_name = '読み込むファイルのパス'; $sample_file = file_get_contents($path_name); |
使用WP_FileSystem读取文件时
1 2 3 4 5 6 7 8 9 | <?php //file.phpの読み込み(ABSPATHは、WordPressのインストールされたパス名を返す定数) require_once(ABSPATH.'wp-admin/includes/file.php'); $path_name = '読み込むファイルのパス'; if(WP_Filesystem()){ global $wp_filesystem; $sample_file = $wp_filesystem->get_contents($path_name); } |
写文件
使用file_put_countents函数写入文件时
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $path_name = '書き込むファイルのパス'; //新規ファイルを作成する場合 $new_file_text = "新規テキスト\n"; file_put_contents($path_name,$new_file_text); //既存のファイルに追記する場合 $add_text = "追加テキスト\n"; //FILE_APPENDフラグはファイルの最後に追記することを意味します。 //LOCK_EXフラグは他の人が同時にファイルへの書き込みをできないようにすることを意味します。 file_put_contents($path_name, $add_text, FILE_APPEND | LOCK_EX); |
使用WP_FileSystem写入文件时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php //file.phpの読み込み(ABSPATHは、WordPressのインストールされたパス名を返す定数) require_once(ABSPATH.'wp-admin/includes/file.php'); $path_name = '書き込むファイルのパス'; //新規ファイルを作成する場合 if(WP_Filesystem()){ global $wp_filesystem; $new_file_text = "新規テキスト\n"; $wp_filesystem->put_contents($path_name,$new_file_text); } //既存のファイルに追記する場合 if(WP_Filesystem()){ global $wp_filesystem; $sample_file = $wp_filesystem->get_contents($path_name); $sample_file .= "追加テキスト\n"; $wp_filesystem->put_contents($path_name,$sample_file); } |
摘要
将PHP标准函数与WP_FileSystem进行比较,使用WP_FileSystem的描述方法稍长一些,但是通过编写此代码,您可以根据WordPress准则实现表单。因此,如果您想使用WordPress操作文件,我认为您应该使用WP_FileSystem。