2

I am trying to create multiple files in PHP using a foreach loop. The foreach loop reads the contents of an array, which is formed using file() function from a text(.txt) file. The loop is supposed to create a [.php] file with EACH of the value in the array, but it is creating the file for ONLY the LAST value in the array.

<?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
  • whats the output of $user_list? Commented May 29, 2017 at 8:43
  • Rafael Shkembi the output is correct, exactly what I want. Commented May 29, 2017 at 8:56

2 Answers 2

1

If you work with multiple fwrite(), need to be close file handler by fclose() after writing file was completed:

<?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);
        }

    } 
?>
Sign up to request clarification or add additional context in comments.

6 Comments

I used fclose() after you said, still only the LAST value is printed.
I removed the counter($n) but that still didn't help. It even created problem when I was printing [hyperlinks]. Still only the last value's file is created.
User a instead of a+ parameter of fopen()
I used the parameters 'a' , 'x' and 'w' as well, still no good. :(
how $user_list=file('users.txt'); return array? It's string! What's content of users.txt file?
|
0

The problem is as you are reading from text file, there have a lot of chance of adding a space suffixed with the data in the array., i used trim() method and it worked fine for me, A suggestion, use file_exists () function to check if directory exists. the following code worked for me i hard coded the user name .

<?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);
        }

    } 
?>

2 Comments

@Mrigank Pawagi try this once
Thanks a lot bro..! I used trim and now ALL the files are created. Thanks a lot for your help. Just check out mrigankpawagi.github.io one my project is finished!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.