Alesfatalis
Alesfatalis

Reputation: 777

php problems saving array to textfile

Hey guys im trying to save the values into an textfile. I tried different ways and always when i open the textfile all the values are written in one line without space. I want to write each value in its own line here is what i have so far:

    $filename = 'admin_liste.txt';
    $string   = '';

    foreach($arr as $key => $val) {
    $string .= "$val\n";
    }

    file_put_contents($filename, $string); 

This writes everything like this in the textfile: user1user2user3user4

But i want it like this:

Without the "●"

Upvotes: 0

Views: 289

Answers (4)

Ifthikhan
Ifthikhan

Reputation: 1474

Since you are working on windows you should use '\r\n'. I suggest that you use the built-in constant PHP_EOL as it would render the newline character based on the platform your are currently running.

EDIT

Added the PHP_EOL to your snippet and seems to work.

$filename = 'admin_liste.txt';
$string   = '';
$arr = array('user1', 'user2', 'user3');

foreach($arr as $key => $val) {

    $string .= "$val" . PHP_EOL;

}

file_put_contents($filename, $string);

Upvotes: 3

Ben Carey
Ben Carey

Reputation: 16968

You are using the Linux newline character, you need to use the \r\n for windows.

So your code will look like this:

$filename = 'admin_liste.txt';
$string   = '';

foreach($arr as $key => $val) {
    $string .= "$val\r\n";
}

file_put_contents($filename, $string);

However, PHP has a built in constant which will handle this dependant on the operating system you are running. So instead of using the above, you could simply use the following (no point if your website is always going to be on Windows though, but point to know):

file_put_contents($filename, implode(PHP_EOL,array_values($arr)));

Upvotes: 4

Daxen
Daxen

Reputation: 527

Try this code

 $filename = 'admin_liste.txt';
$string   = '';

foreach($arr as $key => $val) {
$string .= "$val\n\r";

}
file_put_contents($filename, $string); 

Upvotes: 0

Igor Mancos
Igor Mancos

Reputation: 314

You can simple use PHP_EOL constant

file_put_contents($filename, implode(PHP_EOL,array_values($arr)));

Upvotes: 0

Related Questions