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

2 replies
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?
#file #function #php #text #write
  • Profile picture of the author aesoft
    Originally Posted by Brandon Tanner View Post

    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!";
    }

    = test_function ();

    = "test_file.txt";
    = fopen(, 'w');
    fwrite(, );
    fclose();

    ?>


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

    Any idea what I'm missing here?
    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.
    {{ DiscussionBoard.errors[3001373].message }}
    • Profile picture of the author Brandon Tanner
      Very cool, James. Thanks for your help!
      Signature

      {{ DiscussionBoard.errors[3001413].message }}

Trending Topics