4

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>

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A year later, and I'm using Smarty. It's awesome! Thanks!
1

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>

Comments

1

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.

Comments

0

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.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.