dealing with large HTML output via plugin code

@Byran M. I tend to use two constructs I don’t often see other WordPress developers using often, which surprises me, but I like them a lot.

1.) Heredocs

You can store large blocks of text as heredocs string that might look like this so I can store worrying about mixing single and double quotes:

   $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;

Note that the variables might be passed to a function as an array and then extract()ed or you could assign them in other ways. Also note that I use the braces not because they are always required but they make the code easier to read. (Of course with functions like the_content() being materially different from get_the_content() WordPress doesn’t always make this style of coding easy.)

What’s more, although it may not be relevant to you is if I use heredoc names like HTML, SQL, etc. then my IDE PhpStorm does syntax injection and will give me autocomplete and syntax coloring within the heredoc.

2.) String Concatenation using an Array

The other idiom I like to use is to collect the content into an array and then implode() the array. Although I’ve never benchmarked this so it could be less helpful than I assume I do know that repeated string concatenation is a killer as strings get larger (if anyone knows why this approach isn’t any better or if you know a better approach I’d love to hear feedback):

function my_get_form_and_fields($input_items) {
    $html = array();
    $html[] = '<form name="my_form" method="get">';
    foreach($input_items as $input_item) {
        extract($input_item);
        $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;
    $html[] = '</form>';
    return implode("\n",$html);         
}   

Leave a Comment