This is an example of using fopen() to create a file, fwrite() to write to the file, and fclose() to close the file. Most common method for creating and writing to text files that involve complex data structures such as arrays. Can use the file() function to retrieve the data as an array for advanced data manipulation, such as sorting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP Working with Text Files Example 1</title> <link rel="stylesheet" href="../php_styles.css" type="text/css" /> </head>
<body> <div align="center"> <h3>Add a Bowler</h3> <form action="script.php" method="get"> <label>First Name </label><input type="text" name="fname" /> <label>Last Name</label><input type="text" name="lname" /> <input type="submit" name="submit" value="Add" /> </form> </div> </body> </html>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP Working with Text Files Example 1</title> <link rel="stylesheet" href="../php_styles.css" type="text/css" /> </head>
<body> <?php if (empty($_GET['lname']) || empty($_GET['fname'])) { echo '<div align=center>Please enter your first and last name. Click <a href="javascript: history.go(-1)">here</a> to return to the form.</div>'; } else { $lname = $_GET['lname']; $fname = $_GET['fname']; $file = "bowlers.txt"; $BowlersFile = fopen($file, "a"); $NewBowler = $lname . ", " . $fname . "\n"; fwrite($BowlersFile, $NewBowler); fclose($BowlersFile); echo '<div align=center><p>' . $NewBowler . ' has been added.</p>'; echo '<p>Click <a href="http://php.skillbuilderblocks.com/tutorials/unit05/ex01/form.php" target="unit05content">here</a> to return to the form.</div></p>'; } ?> </body> </html>
|
Hurr, Ben
Hurr, Ben
Hurr, Ben
Hurr, Ben
Stewart, Martha
Smith, Jimmy
Zappa, Frank
Marrs, Kathy
Twain, Mark
Twain, Mark
Spencer, Sue
Laning, Paul
boyd, james
black, joe
Utihctlg, Utihctlg
pcdgnmc, pcdgnmc
pcdgnmc, pcdgnmc
wkycoklnhi, wkycoklnhi
wkycoklnhi, wkycoklnhi
Ebpukcwo, Ebpukcwo
Ykswoxuo, Ykswoxuo
gghmfu, gghmfu
gghmfu, gghmfu
fiygmcwmh, fiygmcwmh
fiygmcwmh, fiygmcwmh
nherbog, nherbog
nherbog, nherbog
Cwbfwrex, Cwbfwrex
Omqtgdbg, Omqtgdbg
Ccfljovk, Ccfljovk
Sagzmlji, Sagzmlji
Xjxcsqed, Xjxcsqed
Sofwjfit, Sofwjfit
Ombrypyh, Ombrypyh
Mpmqjnfj, Mpmqjnfj
Ahsaketc, Ahsaketc
Xebbdlfz, Xebbdlfz
Btocchng, Btocchng
Rimjhtva, Rimjhtva
pjioefvhb, pjioefvhb
pjioefvhb, pjioefvhb
hoking, hoking
hoking, hoking
sally, sally
sally, sally
Mark, Mark
Mark, Mark
Mark, Mark
Mark, Mark