<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<body>
<?php
/*
* fopen() * returns "file handle"
*
* fread() *
*/
/*
// this does NOT work!
$file =
'http://localhost/testFolder/tetsuro/tetsuroP03_php_file/RandomSentences.txt'
or die('Could not open file!');
*/
// this works
$file =
'C:\wamp\www\testFolder\tetsuro\tetsuroP03_php_file\RandomSentences.txt'
or die('Could not open file!');
/*
// this works too
// note: the file is in the same folder as this php file.
$file = 'RandomSentences.txt' or die('Could not open file!');
*/
// open file
$fh = fopen($file, 'r') or die('Could not open file!');
// read file contents
$data = fread($fh, filesize($file)) or die('Could not read file!');
//
// some debug stuff
//
echo "<br /><br />";
$size=filesize($file);
echo "total bytes in the file is $size";
echo "<br />";
echo "this is what's in the file handle: $fh";
echo "<br /><br />";
// close file
fclose($fh);
// print file contents
echo $data;
echo "<br /><br />";
/*
* file() * opens the file, reads it into an array and closes the file - all in one
*
* foreach() * using loop, use this command to read array
*
*/
echo 'using file()';
echo "<br /><br />";
$file =
'C:\wamp\www\testFolder\tetsuro\tetsuroP03_php_file\RandomSentences.txt'
or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
echo $line;
}
echo "<br /><br />";
/*
* file_get_contents() * reads the entire file into a string - all in one
*
*/
echo 'using file_get_contents()';
echo "<br /><br />";
$file =
'C:\wamp\www\testFolder\tetsuro\tetsuroP03_php_file\RandomSentences.txt'
or die('Could not open file!');
// read file into string
$data = file_get_contents($file) or die('Could not read file!');
// print contents
echo $data;
echo "<br /><br />";
?>
</body>
</html>
No comments:
Post a Comment