tags:

views:

70

answers:

4

Currently I'm using

<pre><code> code here </code><pre>

to display code. I'm pulling this information from a DB for a blog. The problem I'm having is that some of the code isn't showing. For example, in the source code I have this:

<pre><code><br />
echo '<ul class="mylist"><li><ul class="left">';
foreach($nameArray as $name) {
    if($countervar == $half) {
        echo '</ul></li>';
        echo'<li><ul class="right">';
    }
    echo '<li>$name</li>';
    ++$i;
}
echo '</ul></li>';    
echo '</ul>';
?>

But all that shows up is this:

echo '';
foreach($nameArray as $name) {
if($countervar == $half) {
echo '';
echo'';
}
echo '$name';
++$i;
}
echo '

An there's some really weird formatting/spacing issues as well. Any ideas as to what is causing this? I should also mention that some of the other sets of code show up just fine.

+3  A: 

You need to HTML escape the code before echoing it using the htmlspecialchars function.

SLaks
The problem with that is I don't need to escape the WHOLE post, just the parts that have code. So how do I escape only parts of the post between <pre> and </pre>?
WillyG
I'm not sure what you mean.
SLaks
+1  A: 

is it escaped? if not, there is htmlspecialchars.

sreservoir
A: 

If you have XHTML you can also use CDATA sections. They are generally more readable (and pretty!) than a text with HTML encoded entities. Just don't forget to replace occasional ]]> sequences with ]]>]]&gt;<![CDATA[

codeholic
A: 

As others have said, using htmlspecialchars()/htmlentities() will work however there is a builtin function for doing PHP syntax formatting - checkout highlight_string() and highlight_file(). And if you want even more flexibility / control have a look at Geshi

C.

symcbean