Problem when loading php file into variable (Load result of php code instead of the code as a string)

前端 未结 5 1651
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 03:47

I have a site architechure where I assign content to variables and then print them in a master page. My problem is that php code in the sub pages is imported into the variab

相关标签:
5条回答
  • 2020-12-04 04:13
    <?php
        $page_content = "./include/signup_content.php";
        $page_header = "./include/signup_header.php";
        include('master.php');
    ?>
    

    and

    <!DOCTYPE HTML>
    <html>
    <head>
        <?php include $page_header; ?>
    </head>
    
    <body id="home">
        <div class = "container">
           <?php include $page_content; ?>
        </div>
    </body>
    </html>
    

    that's all

    I hope that signup_content.php contains the similar template only

    0 讨论(0)
  • 2020-12-04 04:26

    in signup.php use

    <?php
    $page_content = include("./include/signup_content.php");
    $page_header = include("./include/signup_header.php");
    include('master.php');
    ?>
    

    that is what you need.

    0 讨论(0)
  • 2020-12-04 04:32

    file_get_contents returns the actual contents of a file, what you need is include, which actually parses a PHP file.

    0 讨论(0)
  • 2020-12-04 04:33

    use can use eval function

    http://php.net/manual/en/function.eval.php

    $string = eval('?'.'>'.file_get_contents('signup_content.php',1).'<'.'?');
    echo $string;
    
    0 讨论(0)
  • 2020-12-04 04:35

    Using file_get_contentsDocs will return the actual file's content. But you're looking to execute the file instead. You can use includeDocs to execute a php file, however most often that file will create output itself already. This is probably not what you want.

    Instead, you can still use include but catch the output into a buffer. This is called output-buffering Docs.

    To make this more accessible for your program, you can create a small helper function that deals with the details. You can then just call that function that will include the file in question and return the actual output. You can then assign the return value to your variables.

    Example:

    <?php
        /**
         * include_get_contents
         *
         * include a file and return it's output
         *
         * @param string $path filename of include
         * @return string
         */
        function include_get_contents($path)
        {
            ob_start();
            include($path);
            return ob_get_clean();
        }
    
        $page_content = include_get_contents("./include/signup_content.php");
        $page_header = include_get_contents("./include/signup_header.php");
        include('master.php');
    ?>
    

    Related: Answer to Modify an Existing PHP Function to Return a String

    0 讨论(0)
提交回复
热议问题