使用foreach循环在PHP中创建多个文件,用于使用file()函数创建的数组

时间:2017-05-29 08:42:37

标签: php arrays file loops foreach

我正在尝试使用foreach循环在PHP中创建多个文件。 foreach循环读取数组的内容,该数组是使用文本(.txt)文件中的file()函数形成的。该循环应该创建一个[.php]文件,其中包含数组中EACH的值,但它只为数组中的LAST值创建文件。

<?php
$user_list=file('users.txt');
$n=0;
foreach ($user_list as $user[$n]) {
if(!file_exists("Users/".$_POST[username]."-".$user[$n].".php")){
$file_c=fopen("Users/".$_POST[username]."-".$user[$n].".php", 'a+'); 
fwrite($file_c,"Content");  
}
$n++;
} 
?>

2 个答案:

答案 0 :(得分:1)

如果您使用多个fwrite(),则在写完文件后需要通过fclose()关闭文件处理程序:

<?php
    $user_list=file('users.txt');

    foreach ($user_list as $user) {
        if(!file_exists("Users/".$_POST[username]."-".trim($user).".php")){
            $file_c=fopen("Users/".$_POST[username]."-".trim($user).".php", 'a'); 
            fwrite($file_c,"Content");
            fclose($file_c);
        }

    } 
?>

答案 1 :(得分:0)

当您从text file读取问题时,有很多机会在数组中添加space后缀。我使用了trim()方法并且它为我工作得很好,一个建议,使用file_exists ()函数来检查目录是否存在。以下代码对我有用,我硬编码了用户名。

<?php
    $user_list=file('users.txt');
    $username = 'sdcds';

    foreach ($user_list as $user) {
        if(!file_exists('Users/'.$username."-".trim($user).".php")){

            $file_c = fopen('Users/'.$username."-".trim($user).".php", 'a+'); 
            fwrite($file_c,"Content");
            fclose($file_c);
        }

    } 
?>