0

我正在使用 codeigniter 生成一个用于插入模板视图的 html 表。在如何在生成的 html 代码中插入换行符和一些实验的帮助下,我已经能够将我的代码更改为:

$string='<table id="myDataTable" class="table table-bordered table-striped" style="clear: both">\n <tbody>\n';

    foreach ($array as $key => $value) {

    $string=$string."\t\n<tr><td>$key</td>";  
    $element='<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.'</tbody>\n</table>';

然后我将这个生成的 html 字符串注入到我的 CI 视图中,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
   <base href="<?=base_url();?>">
    <meta charset="utf-8">
    <meta name="author" content="Vitaliy Potapov">
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
   <link href="css/bootstrap.css" rel="stylesheet">
   <link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.4.5/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet"/>


</head> 
<body> 


  <?=$html_string;?>  


  <script src='js/jquery.js'></script>
  <script src="js/bootstrap.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.4.5/bootstrap-editable/js/bootstrap-editable.min.js"></script>

<script language="javascript" type="text/javascript">

  $(document).ready(function() {
$('#myDataTable').editable();
$.fn.editable.defaults.mode = 'inline';
});

</script>

 </body> 
</html> 

我得到了预期的表格,但由于某种原因,当我查看生成的 HTML 时,我在表格之前看到了一堆生成的换行符。

     \n \n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n  
\n\n

为什么会发生这种情况,我该如何解决?

4

2 回答 2

7

`编辑

我可能与 Orangepill 同时给出了答案,然后编辑了我的答案以给予 Orangepill 信用。


Original answer:

大概是因为$string='';

你需要逃避你的"内心(双引号),并使用:
$string="content with escaped double quotes etc";

在这种情况下,$string所有其他变量必须用双引号括起来才能被视为字符串

根据Orangepill 的回答,连接的使用也是必须的。

于 2013-07-31T19:49:35.017 回答
5

使用单引号时不会插入转义字符。要解决此问题,请从字符串中删除 \n 或将代码更改为以下内容:

<?php
$string='<table id="myDataTable" class="table table-bordered table-striped" style="clear: both">'."\n".' <tbody>'."\n";

foreach ($array as $key => $value) {

    $string=$string."\t\n<tr><td>$key</td>";  
    $element='<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."</tbody>\n</table>";
于 2013-07-31T19:48:50.573 回答