tags:

views:

50

answers:

5

I'm looking for a better way to generate dynamic html from php.

Before I would do something like this:

//generate.php
for(...)
{
    $markup .= '<a id="'.$i.'">link'.$i.'</a>';
}

This is really ugly, and I would much prefer not to have to define my markup inline in php strings.

I am looking for the functionality of include "markup.php";, but I need to be able to store the result into a string, and not output it right away. Something like below would be excellent.

//generate.php
for(...)
{
    $markup .= include "markup.php";
}

//markup.php
<a id="<?=$i?>">link<?=$i?></a>
A: 

Why not throw the php inline? Can you tell us why you need to store it before outputting?

for(...)
{
    ?><a id="<?php echo $i; ?>">link <?php echo $i; ?></a><?php
}

You really shouldn't use short tags.

Josh K
+1  A: 

Use a templating engine such as Smarty TPL. This is what they are.

They both separate the HTML display from the logic and provide convenience functions to generate tedious things like HTML radio buttons.

Borealid
+1  A: 

I believe the second method actually works as long as your included file ends with a return statement. However, why not a template engine such as Smarty?

In Smarty (and I'm sure there are others there are still loops but they are geared toward markup. Also the results of the template aren't output until you call the display() method. This allows you to assign whatever variables you need. Your example would go something like:

PHP:

$links = array('http://stackoverflow.com/','http://google.com'); // whatever you're looping over.
$smarty->assign('links', $links);
// ... other processing ... etc.
$smarty->display('path/to/template.tpl');

Template:

<html>
<body>
{foreach from=$links item=$link }
<a href="{$link}">link {$link}</a>
{/foreach}
</body>
</html>
Cfreak
+1  A: 

You could do:

ob_start();
include 'yourfile.php';
$markup = ob_get_contents();

Check out other functions for output buffering: http://www.php.net/manual/en/ref.outcontrol.php.

jcmoney
A: 

Building on @jcmonkey's suggestion, you could write a function like so:

function markup($i) {
    ob_start();
    include 'markup.php';
    return ob_get_contents();
}

... with a file markup.php which would look like this:

<?php /* I don't like using short_open_tag */ ?>
<a id="<?php echo $i; ?>">link<?php echo $i; ?></a>

You can then call markup() in your for-loop:

for(...)
{
    $markup .= markup($i);
}
LeguRi