qadenza
qadenza

Reputation: 9293

insert content of a file while changing values inside

$title = '';

function insert($file){
    global $title;    
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}

abc.php

<div class='title'><?php echo $title; ?></div>

So I need to insert abc.php while changing variables inside.

In the above (simplified) example I'm expecting lorem ipsum as the result, but I'm getting empty div .title

Upvotes: 0

Views: 45

Answers (2)

ROOT
ROOT

Reputation: 11622

<?php
$template = "<div class='title'>%s</div>";

echo sprintf($template, 'this is title1');
echo sprintf($template, 'this is title2');

Or more readable HTML template, using preg_replace:

PHP code:

$body = file_get_contents('template.html');
$patterns = array(
  '/{title}/'
);
$replacements = array(
  'this is title',
);
$body = preg_replace($patterns, $replacements, $body);

template.html:

<div class='title'>{title}</div>

Upvotes: 1

HP371
HP371

Reputation: 852

As per your current flow it not working.

Try with str_replace in the current file and in abc.php file declare one keyword like #TITLE#

$title = '';

function insert($file){
    global $title;    
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;
}

abc.php

<div class='title'>#TITLE#</div>

Hope this work for you.

Upvotes: 2

Related Questions