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).
it is more comfort to use some template engines. try twig or smarty
Related
I was always curious, is there any significant advantage or disadvantage of writing php inside html or vice versa
example:
echo '<ul>'
foreach ($items as $item)
{
echo "<li>$item</li>";
}
echo '</ul>
As opposed to:
<ul>
<? foreach($items as $item): ?>
<li>$item</li>
<? endforeach; ?>
</ul>
Since these essentially generate the same thing, when would you actually use one over the other?
Functionally they are the exact same and won't have an appreciable affect on performance, if any. It comes down to personal preference and readability - if one is clearer than the other and will be easier for others (or the future you) to understand, go with that one.
I personally find it better to use the latter if you actually have PHP in a mostly HTML file. The clear opening/closing tags match up visually with HTML easier. I find it can be hard to line up curly braces visually.
As an example, in the case of a MVC framework I would use the first way of outputting things in a controller or model context, while the second way in my view files. Some templating languages like smarty have similar looking constructs.
ie:
{ if [condition] }
{ /if }
The first one echoes meaningless strings from the IDE's point of view, whereas the latter one is a mix of HTML and PHP and will be handled properly by your editor. In other words, it's better to actually separate HTML from PHP as it allows your editor to parse HTML and provide some usefull features like syntax validation or autoclosing of HTML tags.
basically php is a server side scripting and html is client side scripting. So if it is php inside html then it generates faster response and you can format a better view. However for some scenario you might have to consider the other case for developing.
Simple HTML DOM is basically a php you add to your pages which lets you have simple web scraping. It's good for the most part but I can't figure out the manual as I'm not much of a coder. Are there any sites/guides out there that have any easier help for this? (the one at php.net is a bit too complicated for me at the moment) Is there a better place to ask this kind of question?
The site for it is at: http://simplehtmldom.sourceforge.net/manual.htm
I can scrape stuff that has specific classes like <tr class="group">, but not for stuff that's in between. For example.. This is what I currently use...
$url = 'http://www.test.com';
$html = file_get_html($url);
foreach($html->find('tr[class=group]') as $result)
{
$first = $result->find('td[class=category1]',0);
$second = $result->find('td[class=category2]',0);
echo $first.$second;
}
}
But here is the kind of code I'm trying to scrape.
<table>
<tr class="Group">
<td>
<dl class="Summary">
<dt>Heading 1</dt>
<dd>Cat</dd>
<dd>Bacon</dd>
<dt>Heading 2</dt>
<dd>Narwhal</dd>
<dd>Ice Soap</dd>
</dl>
</td>
</tr>
</table>
I'm trying to extract the content of each <dt> and put it to a variable. Then I'm trying to extract the content of each <dd> and put it to a variable, but nothing I tried works. Here's the best I could find, but it gives me back only the first heading repeatedly rather than going to the second.
foreach($html->find('tr[class=Summary]') as $result2)
{
echo $result2->find('dt',0)->innertext;
}
Thanks to anyone who can help. Sorry if this is not clear or that it's so long. Ideally I'd like to be able to understand these DOM commands more as I'd like to figure this out myself rather than someone here just do it (but I'd appreciate either).
TL;DR: I am trying to understand how to use the commands listed in the manual (url above). The 'manual' isn't easy enough. How do you go about learning this stuff?
I think $result2->find('dt',0) gives you back element 0, which is the first. If you omit that, you should be able to get an array (or nodelist) instead. Something like this:
foreach($html->find('tr[class=Summary]') as $result2)
{
foreach ($result2->find('dt') as $node)
{
echo $node->innertext;
}
}
You don't strictly need the outer for loop, since there's only 1 tr in your document. You could even leave it altogether to find each dt in the document, but for tools like this, I think it's a good thing to be both flexible and strict, so you are prepared for multiple rows, but don't accidentally parse dts from anywhere in the document.
What is better / faster:
For example:
STATIC / direct HTML:
<?php
for($i=0;$i<$sth;$i++) {
?>
<tr>
<td>
<?php echo $content; ?>
</td>
</tr>
<?php
}
?>
OR
PHP generated HTML:
<?php
for($i=0;$i<$sth;$i++) {
echo "<tr><td>".$content."</td></tr>";
}
?>
Does it matter which option i choose?
Thanks
It's not so much a matter of speed which may vary based on use case, but of making the code clean and maintainable. Actually both examples make for code that's hard to maintain and read.
I'd suggest using a simple and lightweight templating engine to separate all logic from presentation.
I think that there is no substantial difference between the two, the question should be "Which one is more readable" IMHO and i think that using php and html inline is far less readable than echoing php. But that's just my idea.
The better: Generated html.
Generated html with php is far more easy to maintain and easier to read.
The faster: There is no significant speed difference. However on large dynamic websites where content is loaded from a database etc things might take a fraction of a second more time to output. However, the time you spend on updating a static html file is a lot more than editing dynamic content..
Go dynamic :]
In this case "PHP generated HTML" would be quicker because you are only doing one echo where as in "STATIC / direct HTML" you are doing $sth echos. If $sth is zero then "STATIC / direct HTML" would be quicker.
But seriously, the page is parsed and optimised/normalised so it doesn't make any difference. Parsing with less might be quicker because there are less context switches but this is the smallest part (compared to running it) so it makes negligible difference.
Just pick the style that you feel comfortable with.
Two codes represent the same thing, not differentiate in the speed , But the second code may be a little faster because the code does not contain more than one entry and exit signs.
<?php ?>
this will be carried out faster .
The first approach should be faster as it does not involve a lot of string concatenation. It's also better in terms of code readability.
I think the first solution:
It is clearer and do not require php elaborations with string to dispplay simple static content
Is there an standard output library that "knows" that php outputs to html?
For instance:
var_dump - this should be wrapped in <pre> or maybe in a table if the variable is an array
a version of echo that adds a "<br/>\n" in the end
Somewhere in the middle of PHPcode I want to add an H3 title:
.
?><h3><?= $title ?></h3><?
Out of php and then back in. I'd rather write:
tag_wrap($title, 'h3');
or
h3($title);
Obviously I can write a library myself, but I would prefer to use a conventional way if there is one.
Edit
3 Might not be a good example - I don't get much for using alternative syntax and I could have made it shorter.
1 and 2 are useful for debugging and quick testing.
I doubt that anyone would murder me for using some high-level html emitting functions of my own making when it saves a lot of writing.
In regards to #1, try xdebug's var_dump override, if you control your server and can install PHP extensions. The remote debugger and performance tools provided by xdebug are great additions to your arsenal. If you're looking only for pure PHP code, consider Kint or dBug to supplement var_dump.
In regards to #2 and #3, you don't need to do this. Rather, you probably shouldn't do this.
PHP makes a fine HTML templating language. Trying to create functions to emit HTML is going to lead you down a horrible road of basically implementing the DOM in a horribly awkward and backwards way. Considering how horribly awkward the DOM already is, that'll be quite an accomplishment. The future maintainers of your code are going to want to murder you for it.
There is no shame in escaping out of PHP to emit large blocks of HTML. Escaping out to emit a single tag, though, is completely silly. Don't do that, and don't create functions that do that. There are better ways.
First, don't forget that print and echo aren't functions, they're built in to the language parser. Because they're special snowflakes, they can take a list without parens. This can make some awkward HTML construction far less awkward. For example:
echo '<select name="', htmlspecialchars($select_name), '</select>';
foreach($list as $key => $value) {
echo '<option value="',
htmlspecialchars($key),
'">',
htmlspecialchars($value),
'</option>'
}
echo '</select>';
Next, PHP supports heredocs, a method of creating a double-quoted string without the double-quotes:
$snippet = <<<HERE
<h1>$heading</h1>
<p>
<span class="aside">$aside_content</span>
$actual_content
</p>
HERE;
With these two tools in your arsenal, you may find yourself breaking out of PHP far less frequently.
While there is a case for helper functions (there are only so many ways you can build a <select>, for example), you want to use these carefully and create them to reduce copy and paste, not simply to create them. The people that will be taking care of the code you're writing five years from now will appreciate you for it.
You should use a php template engine and just separate the entire presentation and logic. It make no sense for a educated programmer to try to create a library like that.
Just to clarify: The issues "echo vs print" and "double quotes vs single quotes" are perfectly understood, this is about another thing:
Are there any reasons why one would prefer:
echo '<table>';
foreach($lotsofrows as $row)
{
echo '<tr><td>',$row['id'],'</td></tr>';
}
echo '<table>';
over:
<table><?php
foreach($lotsofrows as $row)
{ ?>
<tr>
<td><?php echo $row['id']; ?></td>
</tr><?php
} ?>
</table>
would either one execute/parse faster? is more elegant? (etc.)
I tend to use the second option, but I'm worried I might be overlooking something obvious/essential.
Benefits of first one
Easier to read
???
Benefits of second one
WYSIWYG is possible
HTML Code Completion/Tag-Matching possible with some IDEs
No escaping headaches
Easier for larger chunks of HTML
If I have a lot of HTML in a given PHP routine (like an MVC view) then I definitely use the 2nd method. But I format it differently - I strictly rely on the tag-like nature of PHP's demarcations, i.e., I make the PHP sections look as much like HTML tags as I can
<table>
<?php foreach($lotsofrows as $row) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
</tr>
<?php } ?>
</table>
I agree with Peter Bailey. However, in views I use the alternative syntax for statements, and much prefer short tags (particularly for echoing). So the above example would instead read:
<table>
<? foreach($lotsofrows as $row): ?>
<tr>
<td><?= $row['id']; ?></td>
</tr>
<? endforeach; ?>
</table>
I believe this is the preferred standard for Zend Framework.
The first is far more readable in my opinion, however, the second technically involves less parsing. Any speed advantage in that case would likely be minor and really meaningless without profiling.
Premature Optimization is the root of all evil. Do what makes the code easiest to read and maintain. Efficiency takes a backseat to maintainability.
see http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize for some good advice on the subject
It's very dependable what you write.
PHP can be used as programming language, or as simple and powerful web-template language. Mixing of this two usages very, very bad practice and will be horrible to support in long term.
So Second style is more usable in templates with lot of html markup and little spots of code, first - for 'clear' php programming.
The best one is a template engine.
But, I think echo is way more cleaner and more readable (at least in this case - as pointed out in comments, it depends), than opening and closing tags everywhere (I don't know too much about PHP internals to tell which one is faster, though).
First one is more readable from programming point of view, but the second one allows you to open the file in some WYSIWYG HTML editor and change the page design.
I prefer the second option because it is much easier to tell your designer that "this part of the page will behave like that", than "this piece of code does that"