'PHP - Looking for an HTML Generator/Manager [closed]
I'm trying to find a tool that I can use to generate markup programatically (non-irl word). Here is an example of what I'm trying to accomplish in pseudo-code...
$htmlDoc = new HTML_Document();
$htmlDoc->setTitle('Cool Title');
$htmlDoc->addJs('some_js_file.js');
$htmlDoc->addStylesheet('some_css_file.css');
$divElement = new HTML_Element_Div();
$htmlDoc->append('body', $divElement);
$output = $htmlDoc->generate();
What is the best tool for this?
Solution 1:[1]
I'm working on a simple DSL that addresses this common task. It's called htmlgen, mirrored on packagist.
Here's an example -
use function htmlgen\html as h;
h('#wrapper',
h('h1.title', 'Hello, World'),
h('p',
h('comment', 'link to something'),
h('a', ['href'=>'https://duckduckgo.com'], 'search the internet')
)
);
Here's the output (actual output does not have whitespace)
<div id="wrapper">
<h1 class="title">Hello, World</h1>
<p>
<!-- link to something -->
<a href="https://duckduckgo.com">search the internet</a>
</p>
</div>
It's very new but at ~200 lines of source, it's already very powerful. Fork it and make adjustments or send me a note with suggestions.
Solution 2:[2]
Writing your own simple framework is very simple and is a great learning experience. You can implement this in merely an hour or two, in fact I just did for a recent project only a couple weeks ago.
What I recommend is:
- Create a simple .HTML template with placeholder tags, I use the syntax %HTML_TITLE% and your setTitle method simple does a STR-REPLACE.
- The same holds true for JS, CSS
- Since you may not add certain pieces everytime it's important than it your generate() function you remove any remaining %% tags with a %\w+% regex.
Solution 3:[3]
i'm not aware of such a library, but it would be quite easy to write one, for example, based on XMLWriter.
That said, it's worth noting that php was especially designed to avoid things like this. I'd suggest a templating engine or even 'pure' php for html output.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | TravisO |
| Solution 3 | user187291 |
