How do I load a PHP file into a variable?

后端 未结 8 1436
清歌不尽
清歌不尽 2020-11-30 19:20

I need to load a PHP file into a variable. Like include();

I have loaded a simple HTML file like this:

$Vdata = file_get_contents(\"text         


        
相关标签:
8条回答
  • 2020-11-30 19:40

    Alternatively, you can start output buffering, do an include/require, and then stop buffering. With ob_get_contents(), you can just get the stuff that was outputted by that other PHP file into a variable.

    0 讨论(0)
  • 2020-11-30 19:48

    I suppose you want to get the content generated by PHP, if so use:

    $Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
    

    Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:

    $Vdata = file_get_contents('path/to/YOUR/FILE.php');
    
    0 讨论(0)
  • 2020-11-30 19:59

    If you want to load the file without running it through the webserver, the following should work.

    $string = eval(file_get_contents("file.php"));

    This will load then evaluate the file contents. The PHP file will need to be fully formed with <?php and ?> tags for eval to evaluate it.

    0 讨论(0)
  • 2020-11-30 19:59

    file_get_contents() will not work if your server has allow_url_fopen turned off. Most shared web hosts have it turned off by default due to security risks. Also, in PHP6, the allow_url_fopen option will no longer exist and all functions will act as if it is permenantly set to off. So this is a very bad method to use.

    Your best option to use if you are accessing the file through http is cURL

    0 讨论(0)
  • 2020-11-30 20:00
    ob_start();
    include "yourfile.php";
    $myvar = ob_get_clean();
    

    ob_get_clean()

    0 讨论(0)
  • 2020-11-30 20:01

    If your file has a return statement like this:

    <?php return array(
      'AF' => 'Afeganistão',
      'ZA' => 'África do Sul',
      ...
      'ZW' => 'Zimbabué'
    );
    

    You can get this to a variable like this:

    $data = include $filePath;
    
    0 讨论(0)
提交回复
热议问题