2

Suppose we have something like this:

<?php
while(some statement here)
{
    echo "some HTML here";
    //..................
}
?>

As you know we can do it like this :

<?php
while(some statement here)
{?>
    some HTML here
    ..............
<?php
} ?>

Now,What if I have something like this?

<?php
function example(){
    $out="";
    while(some statement here)
    {
        $out.="some HTML here";
        $out.="some other HTML here";
        //.......................
    }
    return $out;
}
?>

How can I get the HTML code out of <?php ?> so it'll be more readable and can be edited easily using an editor like NotePad++ ? Thanks in advance

Javier Arias
  • 2,329
  • 3
  • 15
  • 26
Vahid2023
  • 863
  • 3
  • 11
  • 33

3 Answers3

3

So if you want better syntax highlighting you need to close the php tags. Output buffering is a clean way to do this and it lets you maintain syntax highlighting in notepad ++. http://php.net/manual/en/book.outcontrol.php

<?php
function example(){
    $foo = "Hello Again";
    ob_start();
    while(some statement here)
    {
        ?>
        <div id="somediv">Hello!</div>
        <div id="somephpvar"><?php echo $foo;?></div>
        <?php 
    }
    return ob_get_clean();
}
?>
Dan Hastings
  • 3,241
  • 7
  • 34
  • 71
  • Thank you Dan,But what if have already started Output Buffering ? – Vahid2023 Jun 30 '17 at 10:52
  • 1
    as far as i am aware, you can still call an output buffer within an already running buffer. https://stackoverflow.com/questions/10441410/what-happened-when-i-use-multi-ob-start-without-ob-end-clean-or-ob-end-flush – Dan Hastings Jun 30 '17 at 10:54
1

Short answer: Use output buffer control (http://php.net/manual/en/book.outcontrol.php)

Example

<?php

function example(){
    ob_start();

    $i = 0;
    while($i < 10)
    {
        ?>
        Hello<br/>
        <?php
        $i++;
    }

    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}


echo example();

Long answer: You'd want to use a template engine like Twig (https://twig.sensiolabs.org/) to have HTML outside of PHP code completely (of course with a lot more of benefit)

Martin Pham
  • 549
  • 4
  • 12
1

If you want to write the function yourself, the best way is using output buffering control, e.g.:

<?php
function() {
    ob_start();
    ?>
     <h1>Hello world</h1>
    <?php
    return ob_get_clean();
}

However, it is higly recommended that you use a template library, such as mustache. Most PHP frameworks include their own template mechanism; have a look at laravel, and cakePHP

Javier Arias
  • 2,329
  • 3
  • 15
  • 26
  • You mean ob_start() and ob_get_clean() . Right? Because I didn't find any function named obp_start() or obp_get_clean() – Vahid2023 Jun 30 '17 at 12:03