views:

94

answers:

2

My code:

$i = 0;
$file = fopen('ids.txt', 'w');
foreach ($gemList as $gem)
{
    fwrite($file, $gem->getAttribute('id') . '\n');
    $gemIDs[$i] = $gem->getAttribute('id');
    $i++;
}
fclose($file);

For some reason, it's writing \n as a string, so the file looks like this:

40119\n40122\n40120\n42155\n36925\n45881\n42145\n45880

From Google'ing it tells me to use \r\n, but \r is a carriage return which doesn't seem to be what I want to do. I just want the file to look like this:

40119
40122
40120
42155
36925
45881
42145
45880

Thanks.

+7  A: 

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

Artefacto
+1 exactly right!
alex
Thanks very much, should have thought of that myself :) I can only accept your answer in 9 minutes but when I can I will.
VIVA LA NWO
A: 

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);
Alix Axel