Shibbir
Shibbir

Reputation: 2031

How to insert PHP code ot new php file using file_put_contents()?

I am trying to insert some PHP code to a new PHP file. To do that I am using:

if ( $this->fblcs_how_to_show == 1 ) {


    $insert_fb_code = <<<INSERTPHPCODE
    <?php 
    global $post;
    $fblcs_permalink    =   get_the_permalink( $post );
    echo  "<div class='fb-comments fbcls-front' data-href='$fblcs_permalink' data-width='' data-numposts='5' data-mobile='true'></div>";
    INSERTPHPCODE;

    file_put_contents( plugin_dir_path( dirname( __FILE__ ) ) . '/public/partials/extra-template/comments-template.php', $insert_fb_code );
}

Now when I open that file where I insert the code it's showing me following code:

<?php 
global $post;
    =   get_the_permalink(  );
echo  "<div class='fb-comments fbcls-front' data-href='' data-width='' data-numposts='5' data-mobile='true'></div>";

you can see that It doesn't add exactly the same content!

can you tell me why and how can I fix it?

Upvotes: 0

Views: 43

Answers (1)

Martin Dimitrov
Martin Dimitrov

Reputation: 1304

What is happening is that it is replacing variables with their values, instead of the names, which are not defined and therefore with no value. What you can do is:

    if ( $this->fblcs_how_to_show == 1 ) {
        $insert_fb_code = '
            <?php 
            global $post;
            $fblcs_permalink    =   get_the_permalink( $post );
            echo  "<div class=\"fb-comments fbcls-front\" data-href=\"$fblcs_permalink\" 
data-width=\"\" data-numposts=\"5\" data-mobile=\"true\"></div>";
    ';

        file_put_contents( plugin_dir_path( dirname( __FILE__ ) ) . '/public/partials/extra-template/comments-template.php', $insert_fb_code );
}

Upvotes: 1

Related Questions