tags:

views:

141

answers:

3

I am trying to display the contents of a .cpp file in php. I am loading it using fread when I print it out it comes out formatted incorrectly. How can I keep the format without escaping each character?

+2  A: 

print it out between the HTML <pre> & <code> tags.

John T
This is what I needed. But how do I get it to display The #include <stdio.h> correctly?
DHamrick
all it displays is #include and then skips the <stdio.h> part
DHamrick
<pre>#include <stdio.h></pre>
John T
+4  A: 

Assuming you want to look at it in a web browser:

<pre>
    <code>
        <?php echo htmlspecialchars(file_get_contents($file)); ?>
    </code>
</pre>
deceze
In fact, the above code snippet is displayed using a `<pre><code>` block...
deceze
avakar
@avakar: Very true, updated answer to reflect that.
deceze
+1  A: 
<?php

echo "<pre><code>";
$filename = "./test.cpp";
$handle = fopen($filename, "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096); // assuming max line len is 4096.
        echo htmlspecialchars($buffer);
    }
    fclose($handle);
}
echo "</code></pre>";

?>

We need htmlspecialchars function to print it out correctly.

antreality