PHP:如何回显包含'和'的字符串

时间:2014-10-08 14:03:28

标签: php html

尝试回应以下

echo (
<script>
$(document).ready(function() {
  $('#example').dataTable( {
    "bPaginate": false,
     "order": [[ 3, "asc" ]],
     "dom": '<"top"lp>',
     "aoColumnDefs": [
          { 'bSortable': false, 'aTargets': [ 0 ] }
       ],
     "aoColumns" : [
          { sWidth: '3%' },
          { sWidth: '45%' },
          { sWidth: '45%' },
          { sWidth: '7%' }
        ]  
  } );
  oTable = $('#example').dataTable();
$('#dataTables_filter').keyup(function(){
      oTable.fnFilter( $(this).val() );
})
} );
</script>
);

正如您所看到的那样,它经常包含大量'"方式,添加\以正确回显它会很痛苦。还有其他方法吗?我在stackoverflow中搜索到目前为止找不到任何东西......

4 个答案:

答案 0 :(得分:2)

使用heredoc字符串:http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

所有内部的内容都是没有引号的字符串:

echo <<<EOT
<script>
$(document).ready(function() {
  $('#example').dataTable( {
    "bPaginate": false,
     "order": [[ 3, "asc" ]],
     "dom": '<"top"lp>',
     "aoColumnDefs": [
          { 'bSortable': false, 'aTargets': [ 0 ] }
       ],
     "aoColumns" : [
          { sWidth: '3%' },
          { sWidth: '45%' },
          { sWidth: '45%' },
          { sWidth: '7%' }
        ]  
  } );
  oTable = $('#example').dataTable();
$('#dataTables_filter').keyup(function(){
      oTable.fnFilter( $(this).val() );
})
} );
</script>
EOT;

小心写下最终标签&#39; EOT&#39;没有任何缩进。

答案 1 :(得分:1)

离开PHP模式。只有在需要处理数据或访问变量时才返回它。

function functionName() {
    ?>
        <script>
           // free text
           var foo = <?php echo json_encode($some_variable); ?>;
        </script>
    <?php
}

答案 2 :(得分:1)

$str = <<<EOF
<script>
$(document).ready(function() {
    $('#example').dataTable( {
    "bPaginate": false,
    "order": [[ 3, "asc" ]],
    "dom": '<"top"lp>',
    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ 0 ] }
    ],
        "aoColumns" : [
        { sWidth: '3%' },
        { sWidth: '45%' },
        { sWidth: '45%' },
        { sWidth: '7%' }
    ]  
} );
oTable = $('#example').dataTable();
$('#dataTables_filter').keyup(function(){
    oTable.fnFilter( $(this).val() );
})
} );
</script>
EOF;

echo $str;

答案 3 :(得分:1)

仅在您需要时才进入PHP模式。