Daily Archives: Wednesday 29/09/2010

PHP: Write to Text File Programming 29 SEP 2010

green php elephants - elephpantsJust a simple code snippet to remind myself just how easy it is to spit out content into a text file using PHP.

As you can see from the code snippet below, to write data to a text file in PHP we make use of three functions, namely fopen, fwrite and fclose.

As its name implies, fopen is responsible for opening the stream. Note the use of the ‘w’ switch which indicates we are opening a stream for writing. This will also force the creation of the file if it doesn’t exist.

The fwrite is used to insert text into the stream and finally the fclose essentially saves the changes and closed the handle opened initially by the fopen call.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, "Text sentence for line 1n");
fwrite($fh, "Text sentence for line 2n");
fclose($fh);

Note, if you wish to append data to an existing file, simply use the fopen function with an ‘a’ switch.

This is demonstrated below:

if (is_writable($myFile)) {
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "Appended text sentence for line 1n");
fwrite($fh, "Appended text sentence for line 2n");
fclose($fh);
}

Simple isn’t it? Don’t know why I keep forgetting it then! O.o

Splittig Gi’s Martial Arts | My Life 29 SEP 2010

Hey, I've even produced a comic on this topic before - told you it happens a fair bit to me! :P

I seem to be making a habit of this you know. Splitting gi’s (or dogis if you prefer) that is.

The latest ripped white training pants to add itself to my notorious list of shredded pants, joined the ranks at Monday night’s training session, where Gerhard and myself were going through the steps for Shisome, the newly renamed first kata under the Funakoshi International style, under the watchful eye of sensei Birgitt.

As I spun around from a nice and relaxed kamae stance into a more bowlegged back stance towards the end of the kata, there was the usual loud ripping noise I’ve become rather accustomed to, prompting an exclamation from sensei as to whose poor knees were giving out now. Shamefully I replied that for a change it wasn’t a body part disagreeing with the sudden movement, but rather my trusty old pants who had now had enough of the incessant abuse I dish out to it every Monday and Wednesday evening.

Come to think of it, it had tried to commit seppuku once before, but my mom jumped to the rescue with needle and thread. This time however there is no saving it, as it has now well and truly committed ritual suicide. (Though it will have to do for tonight’s training over a very white underpants until I can get to the shops on Saturday to try and find a replacement!)

Sigh, me and my ripped pants.

It’s becoming a signature thing I tell you! ;)