PHP - How do you write a function to a text file?

by 2 replies
3
Hey guys,

I'm trying to figure out how to write the output of a custom function to a text file, but there must be something I don't understand about the relationship between functions and writing to a file.

Here's an example of what I'm trying to do...

<?php

function test_function ()
{
echo "Hello!";
}

$function_contents = test_function ();

$file_name = "test_file.txt";
$file_handle = fopen($file_name, 'w');
fwrite($file_handle, $function_contents);
fclose($file_handle);

?>


When I run this script, the text file it creates is blank.

Any idea what I'm missing here?
#programming #file #function #php #text #write
  • Try changing the test_function() to return the value. Right now it's just set to display, "echo", the text.

    Try this:
    Code:
    function test_function ()
    {
    return "Hello!";
    }
    That will return the value "Hello!" to your variable "$function_contents"... which will then contain the value to save in a file.
    • [ 1 ] Thanks
    • [1] reply

Next Topics on Trending Feed