How to assign the contents of a file to a variable in PHP

前端 未结 7 667
Happy的楠姐
Happy的楠姐 2020-12-30 07:22

I have a document file containing HTML markup. I want to assign the contents of the entire file to a PHP variable.

I have this line of code:

$body = in

相关标签:
7条回答
  • 2020-12-30 07:33

    You have two optional choices

    [Option 1]

    1. Create a file called 'email_template.php'
    2. inside the file add a variable like so

      $body = '<html>email content here</html>';

    3. in another file require_once 'email_template.php'

    4. then echo $body;

    [Option 2]

    $body = require_once 'email_template.php';
    
    0 讨论(0)
  • 2020-12-30 07:36

    file_get_contents()

    $file = file_get_contents('email_template.php');
    

    Or, if you're insane:

    ob_start();
    include('email_template.php');
    $file = ob_end_flush();
    
    0 讨论(0)
  • 2020-12-30 07:36

    Try using PHP's file_get_contents() function.

    See more here: http://php.net/manual/en/function.file-get-contents.php

    0 讨论(0)
  • 2020-12-30 07:39

    If there is PHP code that needs to be executed, you do indeed need to use include. However, include will not return the output from the file; it will be emitted to the browser. You need to use a PHP feature called output buffering: this captures all the output sent by a script. You can then access and use this data:

    ob_start();                      // start capturing output
    include('email_template.php');   // execute the file
    $content = ob_get_contents();    // get the contents from the buffer
    ob_end_clean();                  // stop buffering and discard contents
    
    0 讨论(0)
  • 2020-12-30 07:40

    As others have posted, use file_get_contents if that file doesn't need to be executed in any way.

    Alternatively you can make your include return the output with the return statement.

    If your include does processing and outputs with echo [ed: or leaving PHP parsing mode] statements you can also buffer the output.

    ob_start();
    include('email_template.php');
    $body1 = ob_get_clean();
    

    TimCooper beat me to it. :P

    0 讨论(0)
  • 2020-12-30 07:52

    You should be using file_get_contents():

    $body1 = file_get_contents('email_template.php');
    

    include is including and executing email_template.php in your current file, and storing the return value of include() to $body1.

    If you need to execute PHP code inside the of file, you can make use of output control:

    ob_start();
    include 'email_template.php';
    $body1 = ob_get_clean();
    
    0 讨论(0)
提交回复
热议问题