Forum Moderators: coopster

Message Too Old, No Replies

PHP alternate to 'include' function?

need another way to grab content from a flat file

         

frobozz

9:24 pm on Jul 1, 2010 (gmt 0)

10+ Year Member



I need to populate a <textarea> with content from a flat text file. Normally this is easily done with the 'include' command. But this text file contains PHP code, specifically the "<?php" and "?>" syntax, so PHP attempts to parse it and everything falls apart.

I can get around this by opening the text file and manually 'fgetting' each line and dumping it into the textarea, but I'm wondering if there's an easier way. Some alternate to 'include' that instructs PHP to just include the contents of the file without attempting to parse it?

Matthew1980

9:38 pm on Jul 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there frobozz,

I think as this would do the trick:-

<?php
$FileToRead = "PATH_TO_FILE/file.txt";
$FileOpen = fopen($FileToRead, "r");// depending on your need change the setting "r" is read only - given as example
$FileData = fread($FileOpen, filesize($FileToRead));
?>
<textarea><?php echo $FileData; ?></textarea>

That's the way I would approach this anyway..

Cheers,
MRb

Readie

10:07 pm on Jul 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$file = file_get_contents('/path/to/file.txt');


Simpler and preferred to Matt's method above:
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Source: [uk2.php.net...]

Matthew1980

10:23 pm on Jul 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Readie:

Simpler and preferred to Matt's method above:

Conceded, point taken, I was just thinking of the first thing that came to mind :) It would still function thought...

so:-

<?php
$FileToRead = "/path/to/file.txt"
$FileOpen = file_get_contents($FileToRead);
?>
<textarea><?php echo $FileOpen; ?></textarea>

I think that's right, not used file_get_contents in ages

Cheers,
MRb

frobozz

9:33 pm on Jul 2, 2010 (gmt 0)

10+ Year Member



Thank you both, Readie and Matthew1980.

The function 'file_get_contents' is exactly the alternative I was hoping for!

Matthew1980

9:44 pm on Jul 2, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there frobozz,

Both versions work, Readie just pointed out a better/preferred way to do it - I had actually forgotten about file_get_contents. Either way pleased your sorted out now :)

Cheers,
MRb