Forum Moderators: coopster
//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";
}
}
}
}
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"); }
fclose($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.