Jump to content

[SOLVED] use PHP to write a large txt file


mjc

Recommended Posts

I am both new here, and new to PHP (which I'm really loving  :P). I know PHP can help me with this, but can't quite figure it out.

 

I would like to create a plain text file with every number in the range 1 - 1,000,000 (with commas placed correctly each third digit from end). Each number on a new line. The range should be easy to change.

 

I have got this far, be this only gives one number, whereas I would like a file with every number, in order.

 

<?php
$content = "";
for($i=0;$i<100;$i++){
$content = rand(1,1000000) . "\n";
}
$g = fopen("file.txt", 'a');
fwrite($g, $content);
?>

 

 

If you have the time to help, I will be very grateful. If you can explain how the script works as well it will help me learn.

 

thanks in advance,

Try this:

 

<?php
$content = "";
for($i=1;$i<100;$i++){
$content .= number_format($i) . "\n";
}
$g = fopen("file.txt", 'a');
fwrite($g, $content);
?>

 

If you wanted them in order, you shouldn't be using rand(). The number_format() function will add the thousands separator for you. We use the .= operator to append the string to $content so it is not overwritten everytime.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.