Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

How can I write data from a while loop onto a file?

4:50 pm on Sep 11, 2009 (gmt 0)

5+ Year Member

I've been trying to write this while loop onto a file but only been getting 1 data onto the file. I'm trying to make it write all the information from $imagesubject2 to the file. It echos it out and I can see it in view source, but can't get it to write more than one info to the file.

//List files
while ($item = readdir ($dp) ) {
if ( (is_file ($item)) AND (substr($item, 0, 1) != '.') ) {
//Get file size
$fs = filesize ($item);
//Get file modification date
$lm = date ('F j, Y' , filemtime($item));
//Find image
$imagepattern = '/^([0-9]){1,}.jpg$/';
$imagesubject = "$item";
if (preg_match($imagepattern, $imagesubject, $imagematches)) {
//Open file
$imagesubject2 = "<image Thumb=\"tn_$imagesubject\" Large=\"$imagesubject\"/>";
if ($fp = fopen ('test.xml', 'w')) {
fwrite ($fp, "$imagesubject2");
fclose ($fp);
echo "$imagesubject2";
7:00 pm on Sep 11, 2009 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

if ($fp = fopen ('test.xml', 'w')) {

From the docs [us2.php.net]

(w) Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

The equivalent of perl's >, this is overwrite. You are overwriting each entry.

(a) Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Append, the equivalent of perl's >>.

Most people would just use a - appending to a blank file is still appending - but if you are retentive about semantics,

$max_log_size = 100000; // 100K - to prevent it from growing too big to open!
$filemode = (filesize($your_file) >= $max_log_size)?"w":"a";

if (is_writable($your_file)) {
if (!$file = fopen($your_file,$filemode)) { die("Cannot open $your_file in $filemode mode"); }
if (fwrite($file, $your_content) === FALSE) { die("Cannot write to $your_file"); }

An alternative method which will allow you to continue using w - read all your data in, store it all in a variable, then dump it into the file, overwriting it. This might actually be a better solution if your file is relatively small (< 1000 lines.) The reason being, when you append using a loop, you're opening, writing, closing, opening, writing. closing . . . which may get pretty hard on your server's drive. Append to a string variable in your loop, open once, overwrite, close.

The above stores the data in your variable in memory - if you predict this file might grow more than 1000 lines, it might start to hog up memory instead. In this case you might want to stick with what you have, or devise some way to dump into the file (appending) every 1000 lines or so.