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  ($array as $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>' ;
Copy 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>" ;
Copy 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  ($array as $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>' ;
Copy 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  ($array as $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 ;
        }
Copy Solution 5:
 I suggest experimenting with \n and spaces in the echoes, for example: 
$string =$string ."<tr>\n    <td>$key </td>" ;
Copy I believe the result will be:
<tr >
    <td >field1</td >
Copy Edit: Michael's response using \t and \n is way better.
 
 
Post a Comment for "How To Insert Linebreaks In Generated Html Code"