zokopog
zokopog

Reputation: 77

Echo php code as text

I want to echo block of code which is dynamically generated. For example:

<?php
$cid = $camp_id;

$hostname = "$host";
$db_user = "$dbuser";
$db_pass = "$dbpass";
$db_name = "$dbname";

$mysqli = new mysqli();
$mysqli->connect($hostname, $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

etc....
?>

I got access to $camp_id and other variables because they are in the file which is included. I tried to store this code in variable with < pre> and < code> tag and echo after that but couldn't make it work.

Also how can I insert $camp_id to this. Below is example what I think (I know it's not correct just for understanding.

$generated_code = "<.code><?php $cid = <?php echo $camp_id;?> $hostname = $host; etc... </code > ?>";

I used space and dot before code and pre because if not it doesn't show as tag..

Thanks

Upvotes: 1

Views: 7066

Answers (3)

Vitalicus
Vitalicus

Reputation: 1379

Using EOF inside single quote have better result. But No space after 'EOF'

<?php
$head= <<<'EOF'
<?php $var=2; ?>
EOF;
?>

Upvotes: 0

ProdigyProgrammer
ProdigyProgrammer

Reputation: 415

You could also try like this:

<?php
    ob_start();
?>

    <code>$cid = <?php echo $camp_id; ?> , $hostname = <?php echo $host; ?></code>

<?php
    echo ob_get_clean();
?>

Depending on the circumstances and what your code is like, using ob_start() and ob_get_clean() functions allow your code to be more legible in color coded IDEs, since your output wont look like one solid block of color, instead it will be styled like it should in html for better readability.

Upvotes: 1

hakre
hakre

Reputation: 197757

You need to follow the rules for strings in PHP, and next to that you need to follow the rules for HTML, or better, output plain text:

<?php
header('Content-Type: text/plain;');

echo '<?php
$cid = ' . $camp_id .';

etc....

?>';

Upvotes: 1

Related Questions