Tuesday, March 1, 2011

Display c++ code in php

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?

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

    DHamrick : This is what I needed. But how do I get it to display The #include correctly?
    DHamrick : all it displays is #include and then skips the part
    John T :
    #include <stdio.h>
  • 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 `
    ` block...
                                        
    avakar : Note that it's wise to escape special characters like `<`, `>` and `&`.
    deceze : @avakar: Very true, updated answer to reflect that.
  • <?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.

0 comments:

Post a Comment