1

I am using this code to try and read the values in a text file.

$mapFile = fopen('config/map.txt', 'r') or die ("Can't open config file");
while ($line = fread($mapfile,filesize('config/map.txt')))
{
    echo $line;
}

Instead I keep getting this error.

Warning: fread() expects parameter 1 to be resource, null given

I am unsure what I am doing wrong. How can I read the text in the file properly?

UndefinedReference
  • 1,223
  • 4
  • 22
  • 52
  • 1
    Your variable is `$mapFile`, and you're trying to fread `$mapfile`. Variables names are case sensitive. Also, consider `file_get_contents()` instead. – jbafford Jan 14 '16 at 23:52
  • @jbafford `file_get_contents()` isn't really suitable for large files as it loads all the file in memory. Reading a file line by line is far better in any case in my honest opinion. – Loïc Jan 14 '16 at 23:57

3 Answers3

4

PHP variables are case sensitive. $mapFile !== $mapfile.

$mapFile = fopen('config/map.txt', 'r'); // don't need `or die()`
while ($line = fread($mapFile, filesize('config/map.txt')))
{
    echo $line;
}
Ben Harold
  • 6,242
  • 6
  • 47
  • 71
0

Your variable is $mapFile, and you're trying to fread $mapfile. Variables names in PHP are case sensitive. Also, consider file_get_contents() instead, which will open the file, get its entire contents, and close the file, in one function call.

jbafford
  • 5,528
  • 1
  • 24
  • 37
0

You can use the following code to read full file

$file=file('config/map.txt');
foreach($file as $line)
{
echo $line;
}

Or simply

echo file_get_contents('config/map.txt');
jewelhuq
  • 1,210
  • 15
  • 19