DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

29
1 DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida Media Software Design

description

Media Software Design. DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida. The Objectives: Learn how to read a text file into a PHP script. Learn how create a text file from data in a PHP script. Why do I care about Files?. - PowerPoint PPT Presentation

Transcript of DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

Page 1: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1

DIG 3134

Lecture 8: Reading and Writing Text Files

Michael MoshellUniversity of Central Florida

Media Software Design

Page 2: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

2

The Objectives:• Learn how to read a text file

into a PHP script.

• Learn how create a text file fromdata in a PHP script.

Page 3: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

33333333

Why do I care about Files?

Lots of data is available in text files• Price tables• Customer lists• Addresses, e-mail lists

Setting up a complex program is often easierif you use a file.Example: Wheel of Fortune:-- read the cliche’s from a text file-- easily modified to improve gameplay

Jaindiamondtools.com

Page 4: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

444444444

File Paths: Relative

$filename1="cats.txt"; // file is where script is.$filename2="images/cat1.jpg" // file is in sub-directory$filename3="../species/persian.txt" // in SIBLING directory

scriptsmyprogram.php this script contains that stuffcats.txtimages

cat1.jpgpetstore.php

speciespersian.txt

Fulltimewow.blogspot.com

directories areshown in italics

Page 5: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

5555555555

File Paths: absolute, on PC:

$filename1="c:/wamp/www/cats.txt"; // file is where script is.$filename2="c:/wamp/www/images/cat1.jpg" // file is in subdir.$filename3="c:/wamp/www/species/persian.txt" // in SIBLING dir.c: wamp www docroot - - where Apache looks for html & php scripts

myprogram.phpcats.txtimages

cat1.jpgpetstore.php

speciespersian.txt

Fulltimewow.blogspot.com

Page 6: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

66666666666

File Paths absolute: Mac

$filename1="/Applications/MAMP/htdocs/cats.txt"; $filename2="/Applications/MAMP/htdocs//images/cat1.jpg"; $filename3="/Applications/MAMP/htdocs//species/persian.txt";Applications MAMP htdocs docroot scripts

myprogram.phpcats.txtimages

cat1.jpgpetstore.php

speciespersian.txt

Fulltimewow.blogspot.com

Page 7: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

777777777777

File Paths absolute: Unix/Linux(e. g. Sulley)

$filename1="/home/faculty/moshell/public_html/scripts/cats.txt"; $filename2="/home/faculty/moshell/public_html/scripts/images/cat1.jpg"; $filename3="/home/faculty/moshell/public_html/species/persian.txt";/home faculty moshell public_html docroot scripts

myprogram.phpcats.txtimages

cat1.jpgpetstore.php

speciespersian.txt

Page 8: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

888888888888

File Paths absolute: Unix/Linux(e. g. Sulley)

$filename1="/home/student/aa34567/public_html/scripts/cats.txt"; $filename2="/home/student/aa34567/public_html/scripts/images/cat1.jpg"; $filename3="/home/student/aa34567/public_html/species/persian.txt";/home student aa34567 public_html docroot scripts

myprogram.phpcats.txtimages

cat1.jpgpetstore.php

speciespersian.txt

Page 9: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

999999999999

Why would we need absolute paths?

Example:- Perhaps you host websites for three different companies, but

all three need access to common tax tables.- The relative paths from the boutiques, and from Pandaboots,

is different.So, all could use this absolute path:

DocrootPandaBoots $file="c:/wamp/www/taxtables/federal.txt"boutiques

library.forboutiquesSammysTanqueria

taxtablesfederal.txt

Fulltimewow.blogspot.com

Page 10: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

10101010101010101010101010

Code for use on both PC and Mac

1. Use relative paths. Then everything starts from 'docroot'

BUT if your system needs absolute paths, do it this way:

//$Docroot="c:/wamp/www/"; // PC version$Docroot="/Applications/MAMP/htdocs/"; // Mac version

$file=$Docroot."taxtables/federal.txt";

Fulltimewow.blogspot.com

Page 11: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1111111111111111111111111111

Code for use on both PC and mac

1. Use relative paths. Then everything starts from 'docroot'

BUT if your system needs absolute paths, uncomment the right one:

//$Docroot="c:/wamp/www/"; // PC version$Docroot="/Applications/MAMP/htdocs/"; // Mac version

$file=$Docroot."taxtables/federal.txt";

Why not "$Docroottaxtables/federal.txt"; ?

Because PHP will look for a variable $Docroottaxtablesand come up with nothing.

Fulltimewow.blogspot.com

Page 12: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1212121212121212121212121212

Aside: why $Docroot not $docroot?

I use a convention about global variables:

Start their names with $Capital letters. It helps to makeglobal variable instantly recognizable.

Anything that helps my poor old memory is a good thing!!

Fulltimewow.blogspot.com

Page 13: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1313131313131313131313131313

A better way to switch systems

$Computing_environment='pc'; // or 'mac' or 'sulley';// .. And somewhere far below, in the code:if ($Computing_environment=='pc')

$Docroot="c:/wamp/www/";

else if ($Computing_environment=='mac')$Docroot="/Applications/MAMP/htdocs/";

else if ($Computing_environment=='sulley')$Docroot="/home/faculty/moshell/public_html/";

else print "Error 221: unknown computing environment was "."specified:$Computing_environment";

Fulltimewow.blogspot.com

Page 14: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1414141414141414141414141414141414

What's a text file?

It consists of a series of lines of text with some kind of a line separator character (one or more) at the end of each line.

The character used is different on PC and on MAC.But PHP will normally 'smooth out' the difference and hide it.

The "official character" for line separation is a newline, which can be represented by "\n".

Text files can contain numbers, letters and special characters.

An important invisible character is a TAB or "\t".

Lib.utexas.edu

Page 15: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1515151515151515151515151515151515

A Mac-specific problem

Mac treats end-of-line differently.To make sure that the 'file' function reads ALL the linesof a text file, put this at the head of your code:

<?phpsession_start(); // this should be there anywayini_set ("auto_detect_line_endings", true);

Page 16: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

161616161616161616161616161616161616

Our design goal:

Make a simple program that

• Displays a text• Accepts one new line of input• Writes out the text including the new line.

The program will have only two screens:

Screen 1: display the text, and two buttons. UPDATE and QUIT.

Screen 2: If QUIT was selected, report that the text was saved.

Lib.utexas.edu

Page 17: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

17171717171717171717171717171717

Step 1: Build a text-reading function

#textloader:function textloader($whatfile){

if (!file_exists($whatfile)){

print "Sorry, can't find $whatfile.";exit;

}else{

$textarray=file($whatfile);return $textarray;

}}# textloader

EXAM ALERT:Look up andUNDERSTANDEach of theGreen built-infunctions

Page 18: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

1818181818181818181818181818181818

Step 2: Build a text-display function

#textdisplay:function textdisplay($intextarray){ // each item in the $textarray is one line of text.

$linecount=count($intextarray)for ($i=0; $i<$linecount; $i++)

print $intextarray[$i]."<br />";

}# textdisplay

Page 19: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

191919191919191919191919191919191919

Step 3: Get that much working (filedemo1.php)Then build a file writing function.(NOTE: Filedemo1 and filedemo2 in ONE

text file named filedemo.txt, with filedemo3 too!) function textsaver($whatfile,$whattext){

$fp = fopen($whatfile, 'w'); // the 'w' means 'write over the previous contents.'$arraysize=count($whattext);for ($i=0; $i<$arraysize; $i++)

fwrite($fp, $whattext[$i]);fclose($fp);

} # textsaver

Page 20: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

202020202020202020202020202020202020

Putting it all together:Examine filedemo2.php

Some useful functions like makeheader, makefooter

The file i/o functions

The classical if-then-else chain

*** you may steal any or all of this code for use in your

Wheel of Fortune program ****

>>>> You must understand everything in this program, for mastery of the Midterm Exam <<<<<

Page 21: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

212121212121212121212121212121212121

Another example:studentlist.php

I have a class roster (list of student names and NIDS)

I want a class link-list (HTML document to link me to eachperson's Sulley account)

via URLs like http://sulley.cah.ucf.edu/~ni123456

So I created studentlist.php

Examine this code ... understand how it works MTX Material!

Page 22: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

222222222222222222222222222222222222

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want:

$thecharacterslocation value

0 W1 o2 m3 b4 a5 t6 s7  8 hetc etc

Page 23: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

232323232323232323232323232323232323

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want:

$thecharacterslocation value

0 W1 o2 m3 b4 a5 t6 s7  8 hetc etc

here’s one way:for ($i=0; $i<strlen($theline); $i++)

$thecharacters[$i]=substr($theline,$i,1);

Advantage: I built this because I didn’t know anyautomatic way to do it.

Page 24: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

242424242424242424242424242424242424

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want:

$thecharacterslocation value

0 W1 o2 m3 b4 a5 t6 s7  8 hetc etc

here’s another way:

$thecharacters=str_split($theline);

Disadvantage: you have to know about str_split,a built-in function.

Page 25: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

252525252525252525252525252525252525

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want:

$thecharacterslocation value

0 W1 o2 m3 b4 a5 t6 s7  8 hetc etc

A useful test function: print_r ("Print recursive")

$thecharacters=str_split($theline);

Testing the concept: the print_r function.

print_r($thecharacters);

Array ( [0] => W [1] => o [2] => m [3] => b [4] => a [5] => t [6] => s [7] => [8] => h [9] => a [10] => v [11] => e [12] => [13] => n [14] => o [15] => [16] => w [17] => i [18] => n [19] => g [20] => s )

Page 26: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

262626262626262626262626262626262626

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want: Disadvantage of str_split: What if you wantedto push the character in string position 0into the array at location 1?

Like THIS?

$thecharacterslocation value

1 W2 o3 m4 b5 a6 t7 s8  9 hetc etc

Page 27: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

272727272727272727272727272727272727

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want: Disadvantage of str_split: What if you wantedto push the character in string position 0into the array at location 1?

Like THIS?

$thecharacterslocation value

1 W2 o3 m4 b5 a6 t7 s8  9 hetc etc

for ($i=0; $i<strlen($theline); $i++)$thecharacters[$i+1]=substr($theline,$i,1);

Advantage: I built this code, I understand it, I can make it do whatever I want!

Page 28: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

282828282828282828282828282828282828

One final problem:If you have a string and you needan array ... what to do?

example: $theline=”Wombats have no wings”; positions: ”012345678901234567890”;

but we want: RECOMMENDATION:Use this kind of code in your project2

to translate one line of your text fileinto the $letters array.

$thecharacterslocation value

1 W2 o3 m4 b5 a6 t7 s8  9 hetc etc

for ($i=0; $i<strlen($theline); $i++)$thecharacters[$i+1]=substr($theline,$i,1);

Advantage: I built this code, I understand it, I can make it do whatever I want!

Page 29: DIG 3134 Lecture 8: Reading and Writing Text Files Michael Moshell University of Central Florida

292929292929292929292929292929292929

Step by Step, building Project 2

You are of course free to build it in any way you want.

If you need a hint, here are some suggested steps.

• Start with "Wheel of Fortune" starter kit

• Add a copy of textloader & print out the text (to prove it works)

•Add a session variable named $linenumber which recycles (keeping its same value) except when the NEXT PHRASE button was clicked.

(Print this out, to make sure that NEXT PHRASE is working.)

•Now use $linenumber to select a line from the stored text.

like $line=$mytext[$linenumber];

•Finally, add an error message when there is no more text.