2013-03-09 95 views
3

为什么我无法在PHP heredoc中结束JavaScript?</script> in PHP heredoc

下面这行代码的其余部分:

</script> 

变得不是PHP代码部分。他们成为HTML代码。

这就像结束脚本代码结束PHP块。

$headerContent = <<<HEAD 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> 
    <head> 
    <title>$title</title> 
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-2" /> 

    <script> 
    </script> // Here is the problem 
    </head> // code here and below becomes not part of PHP. 
    <body> 
    . 
    . 
    . 
HEAD; 

screenshot for better view

解决这个问题的任何提示?

+0

输出是什么样的? – 2013-03-09 11:13:36

+0

它是相同的*问题* [这里](http://codepad.viper-7.com/T702GS)? – j0k 2013-03-09 11:14:06

+1

@ j0k看起来不像有问题。添加'htmlentities()'看起来像是有效的。 http://codepad.viper-7.com/blvIDG – 2013-03-09 11:19:43

回答

3

虽然我不能HEREDOC重现这个(这是可能的不同版本的PHP的行为不同在这方面),</script>相当于?>在PHP代码,因为它是一个对口<script language="php">。例如:

<script language="php"> $a = 1; </script> 
Test: <?= $a ?> 

因此,无论遇到与?>关闭标签的问题,你也会遇到与</script>结束标记相同的问题。一种选择是将其存储在一个变量中并使用它。例如:

<?php 

$endScript = '</' . 'script>'; 
$headerContent = <<<HEAD 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> 
    <head> 
    <title>$title</title> 
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-2" /> 

    <script> 
    $endScript 
    </head> 
    <body> 
    . 
    . 
    . 
HEAD; 
+0

谢谢,那么我怎么能够将javascript添加到PHP的heredoc? – Boon 2013-03-09 11:23:47

+0

@BoonGǎgǎ,一个想法是将''存储在一个变量中,例如'$ endScript ='';'(以防万一你也遇到了问题),然后在HEREDOC实例中使用'$ endScript'而不是''。 – rid 2013-03-09 11:24:51

+0

非常感谢。你帮了我很多。有用! – Boon 2013-03-09 11:31:53