2013-03-09 58 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