How To Insert Linebreaks In Generated Html Code
I am using codeigniter to generate an html table for insertion into a template view. Unfortunately this is coming out as a very long string on 1 line like: ;
foreach ($arrayas$key => $value) {
$string = $string."<tr>\n\t<td>$key</td>\n";
$element = '\t<td><a href="#" id="'.$key.'" data-type="text" data-pk="'
.$rowID.'" data-url="/post" data-title="'.$key.'">'.$value.'</a>'
.'</td>\n</tr>'."<br>";
$string = $string.$element;
}
$string=$string.'\n\t</tbody>\n</table>';
Solution 2:
You could use the \n
and \t
characters in your loop.
For example:
$string=$string."<tr>\n\t<td>$key</td>\n";
$element='\t<td><a href="#" id="'.$key.'" data-type="text" data-pk="'.$rowID.'" data-url="/post" data-title="'.$key.'">'.$value.'</a>'.'</td>\n</tr>'."<br>";
Also, you shouldn't have a line break after the </tr>
.
Solution 3:
You have to add the line breaks with \n and \t for tabs
$string='<table id="myDataTable" class="table table-bordered table-striped" style="clear: both">\n\t<tbody>\n';
foreach ($arrayas$key => $value) {
$string=$string."\t\t<tr><td>$key</td>\n";
$element='\t\t<td><a href="#" id="'.$key.'" data-type="text" data-pk="'.$rowID.'" data-url="/post" data-title="'.$key.'">'.$value.'</a>'.'</td></tr>\n';
$string=$string.$element;
}
$string=$string.'\t</tbody>\n</table>';
Also br tag is not allowed directly inside table, so I removed it. It doesn't serve any purpose anyways since rows automatically appear on new lines
Solution 4:
You could add the line breaks with \n
and \t
to your $string
variable:
$string='<table id="myDataTable" class="table table-bordered table-striped" style="clear: both">\n\t<tbody>\n';
foreach ($arrayas$key => $value) {
$string=$string."\t\t<tr><td>$key</td>\n";
$element='\t\t<td><a href="#" id="'.$key.'" data-type="text" data-pk="'.$rowID.'" data-url="/post" data-title="'.$key.'">'.$value.'</a>'.'</td></tr>\n'."<br>";
$string=$string.$element;
}
Solution 5:
I suggest experimenting with \n and spaces in the echoes, for example:
$string=$string."<tr>\n <td>$key</td>";
I believe the result will be:
<tr>
<td>field1</td>
Edit: Michael's response using \t and \n is way better.
Post a Comment for "How To Insert Linebreaks In Generated Html Code"