opening file then reading into variable

[problem]

You want to open save the contents of a file, into a variable in PHP.

[/problem]

[solution]

Simple demo on opening and reading contents of files in PHP.

Script under example tab takes filename as a parameter, then opens it read-only and reads contents in data variable.

Then it echoes a header and footer line, with the data in the middle.

[/solution]

[example]

<?php

$filename=$argv[1];
$FH=fopen("$filename","r") or die("could not open $filenamen");

while(!feof($FH)) { $data.=fgets($FH); }

fclose($FH);

echo "###### beginning of $filename ######n";
echo "$data";
echo "n###### end of $filename ######n";

exit(0);

?>

Here is a run through:


$ php -q readfiles.php rhyme.txt
###### beginning of rhyme.txt ######
Mary had a little lamb,
It was always bleating.
###### end of rhyme.txt ######

[/example]

[reference]

[tags]PHP file handling, PHP Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *