how to write php code to a file with php

后端 未结 6 629
梦如初夏
梦如初夏 2020-12-20 18:37

For part of my website I need to be able to write php code to a file with php. For example:

$filename = \"RtestR.php\";
$ourFileName =$filename;
$ourFileHand         


        
相关标签:
6条回答
  • 2020-12-20 19:00

    It seems relevant to mention php's HEREDOC in this context, e.g.:

    <?php
    $filename      = 'RtestR.php';
    $ourFileName   = $filename;
    $ourFileHandle = fopen($ourFileName, 'w');
    
    $write =  <<<"FILE_CONTENTS"
    <p>I like the color <?={$cleanSessionVars[ 'color' ]};?>.</p>
    
    FILE_CONTENTS;
    
    fwrite($ourFileHandle, $write);
    
    fclose($ourFileHandle);
    
    0 讨论(0)
  • 2020-12-20 19:07

    Finally figured this out! I needed to escape my $ symbols! Like this:

    $written =  "
    <html>
    <body>
    <?php
    echo \"I like the color \".\$_SESSION['color'].\"!!!!\";
    </body>
    </html>
    
    ";
    

    Can't believe i didn't think of that ;)
    Thank you all!

    0 讨论(0)
  • 2020-12-20 19:11

    Hello pattyd: Nice to see ya :) + Don't upvote/accept this answer:

    I would suggest simplified in this way:

    $written =  "
        <html>
            <body>
               I like the color \" $_SESSION['color'] \" !!!!
            </body>
        </html>
    ";
    
    0 讨论(0)
  • 2020-12-20 19:11
    $fp = fopen("test.php", "w");
    $string = '<html>
        <body>
        <?php
        echo "I like the color ".$_SESSION[\'color\']."!!!!";
        ?>
        </body>
        </html>';
    
    fwrite($fp, $string);
    
    fclose($fp);
    
    0 讨论(0)
  • 2020-12-20 19:13

    You can do like this :-

        <?php
    
        $filename = "RtestR.php";
        $ourFileName =$filename;
        $ourFileHandle = fopen($ourFileName, 'w');
    
    
    
        $written =  "<html>
                        <body>          
                            I like the color ".$_SESSION['color']."!!!! 
                        </body>
                    </html> ";
    
        fwrite($ourFileHandle,$written);
    
        fclose($ourFileHandle);
    
    ?>
    
    0 讨论(0)
  • 2020-12-20 19:20

    You're missing your closing PHP tag ?>.

    Consider for a moment that what you are doing might not be the best approach anyway. The only use case I can think of for writing out PHP files with PHP would be for some compiled template code or weird caching.

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