I find myself lately working with a ton of tabular data, I am more than comfortable writing the raw html but i'm wondering if there's an easier way (or library worth implementing) that helps reduce time writing html tags such as
<tr><td></td></tr>
I have created my own custom function, but I think ultimately it's not necessarily helping and potentially could be slowing down my script, now my project is small so maybe it could cope with that, examples:
echo '<tr class="test_class">
<td>' . $content . '</td>
<td>' . $second_content . '</td>
<tr/>';
here is an example with my current function:
tr("test_class");
td(); echo $content; escape(td);
td(); echo $second_content; escape(td);
escape(tr);
Looking forward to hearing peoples thoughts.
There are multiple ways of doing this...
write your own html helper library, that will contain classes, that can generate html elements based on their data source. For instance you could call them like:
<?php
HtmlHelper::Table("someArrayOfValues", "idOfTable", "styleOfTable");
?>
This is a good reusable solution, if you implement this idea properly. I was playing with this myself few days ago, really it's simple.
if you find 1. difficult, you can split the idea down... But not so deep like you've shown, but generate whole rows instead.
<?php
foreach ($myArray as $key => $value)
{
echo HtmlHelper::Row(...);
}
?>
Find some library, that provides this functionality. Can't help you on this one I'm afraid. I like to have control over the generated markup.
Hope you get the idea.
If you have short_open_tags
turned on (and assuming you can turn it on, if necessary), you can use the templating syntax, like this:
<table>
<?php foreach($myList as $key => $value): ?>
<tr>
<td><?= $value["key1"] ?></td>
<td><?= $value["key2"] ?></td>
...
</tr>
<?php endforeach; ?>
</table>
That might make your job easier, in terms of writing tabular data.
The biggest strength of PHP for web development is how much its made to do with few calls, and in particular for this case the echoing of content without the need to work through language constraints. So in general unless the case is really warranted, directly writing the html with the echoes will be the simplest solution that takes the most advantage of PHP, and simplicity is always a good thing.
That being said, if you have a lot of complex table generation, then the code would be more readable if use a library like: http://pear.php.net/package/HTML_Table/. Additionally if you were looking to do something like serialize an object into a table display, then creating a serializer that is made for that would be the solution most in-line with the functionality.
In the code above I'd suggest a transparent utility function certainly wouldn't hurt. But rather than the direction you're going if you consistently have the same number of columns then you could use an array which is joined with the table cell separation markup (a function that produces a row at a time).