Re: create file and write content in same code block



leon.san.email@xxxxxxxxx wrote:
This a modified part of a larger script I made. I couldn't get it
working so I made a smaller part of it - hoping to get it working.
Well it still doesn't work :(
The following code creates the new file, but does not write the
$content strings to the file. It then prints "Did nothing!" instead of
"done!".

<?php

$word = "2002";

$content1 = "one ";
$content2 = "two ";
$content3 = "three";

$fileName = '/home/leke/www/dic/' . $word . '.html';
$handle = fopen($fileName, 'w');
if (file_exists($fileName)) {
print "Did nothing!";
}
else
{
fwrite($handle, "$content1 . $content2 . $content3");
fclose($handle);
print "done!";
}
?>

I cant figure out the problem. Can anyone help me and maybe explain
what went wrong?
Thanks :)

The fopen($filename,'w') function will create the file. Therefore, the file exists, and file_exists() will return true, causing the code to take the "Did nothing" branch.

Try this:

$fileName = '/home/leke/www/dic/' . $word . '.html';

if (file_exists($fileName)) {
print "Did nothing!";
}
else
{
$handle = fopen($fileName, 'w');
fwrite($handle, "$content1 . $content2 . $content3");
fclose($handle);
print "done!";
}

Of course, you probably want to add some error checking after the fopen() call to make sure the file was created properly before writing to it, but this sequence should work.

.



Relevant Pages

  • Re: Putting a line in a specific place in a file
    ... A file is really a sequence of bytes, no more, no less. ... another tool that makes files look like a sequence (a Perl array) of lines. ... Yeah, Tie::File is great, but I needed to learn the steps in writing my ...
    (comp.lang.perl.misc)
  • Re: Internally generated spam - but from where?
    ... I have found the script that is responsible for this *, ... data posted to it so i cant see how they are actually breaking it but I ... How can i track down what is causing ... this single process to use up so much CPU? ...
    (comp.mail.sendmail)
  • Re: elements of odd order
    ... I do not see any harm in writing a ... It's not a problem of writing sequence of equations. ... exponents and complex exponents like "^". ...
    (sci.math)
  • Re: Switching to Linux, now what to buy?
    ... No analytic resolution. ... Don't I know any simple sequence that increases in this somewhat ... Actually I concluded from writing the first post that the solution ... barrier by looking hard at the search space definition. ...
    (comp.os.linux.setup)
  • Re: Cantors definition of set
    ... that mathematics has not given us an axiom of order, ... but in the end I couldn't because I have to respect good writing. ... We might then say that this ascending series is an example of ... There is a notion of sequence. ...
    (sci.logic)

Loading