Jump to content

Function to print PHP code within code?


benphp

Recommended Posts

I want to print PHP code to a page without running it in a PHP file. I know there's got to be some function that does this.

 

here is one way:

 

<HTML>
<BODY>
<?php

$string=<<<stringend

<?php

for (\$i=0;\$i<10;\$i++) {
    echo "hello world<BR>";
}

?>

stringend;

$string = nl2br(str_replace(" "," ",htmlspecialchars($string)));

echo $string;

?>
</BODY>
</HTML>

 

output in browser:

 

<?php

for ($i=0;$i<10;$i++) {
    echo "hello world<BR>";
}

?>

 

there must be a way without having to escape vars....

If php code is enclosed in single-quotes, variables won't be parsed.

 

You also need to use htmlentities() with the second parameter set to ENT_QUOTES so that special HTML characters (<, >, ', ") that have meaning in the browser are not operated on by the browser.

 

You might also want to look at the highlight_string() or highlight_file() functions to get php to do this for you (with some color highlighting included.)

yes, good ones. actually ENT_QUOTES is not required and you may need ENT_NOQUOTES depending on the situation. i tried all 3 with the same results in my example.

 

<HTML>
<BODY>
<?php

$string='<?php

for ($i=0;$i<10;$i++) {
    echo "hello world<BR>";
}

?>

';

$string = nl2br(str_replace(" "," ",htmlspecialchars($string, ENT_QUOTES)));

echo "<DIV>".$string."</DIV>";

?>
</BODY>
</HTML>

 

i have no experience with those functions. i will have to look into them.

Okay - I have to share this one. I'm using THIS forum to format my PHP. I preview the code, then select the preview table and view selected source (Firefox lets you do that). The result is a beautifully formatted, colored PHP script. When you view source, look for

 

<td class="post" id="preview_body" width="100%">

 

Copy that entire line, and you have your formatted HTML.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.