【问题标题】:</script> in PHP heredocPHP heredoc 中的 </script>
【发布时间】:2013-02-24 22:35:42
【问题描述】:

为什么我无法在 PHP heredoc 中结束 javascript?

此行下面的其余代码:

</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;

有解决这个问题的技巧吗?

【问题讨论】:

  • 输出是什么样子的?
  • 是不是一样的问题 here ?
  • @j0k 看起来没有问题。添加htmlentities() 看起来可行。 codepad.viper-7.com/blvIDG
  • 提示一下——我曾经很喜欢 heredocs,但现在我非常讨厌他们。它们令人讨厌的原因有很多,但对我来说主要是它们不能缩进——开始和结束都必须向左对齐。这使得复杂的代码很难处理。我经常希望我能及时回到过去,警告自己不要使用它们!
  • @RichBradshaw 感谢您的提示。由于我已经实现了 heredocs,而我的任务现在需要我将 javascript 集成到我的网站中,无论如何要让它成为可能?更改整个代码非常繁琐。

标签: php javascript heredoc


【解决方案1】:

虽然我不能用 HEREDOC 重现这一点(不同版本的 PHP 在这方面的行为可能不同),&lt;/script&gt; 相当于 PHP 代码中的 ?&gt;,因为它是 &lt;script language="php"&gt; 的对应物。示例:

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

因此,无论您遇到?&gt; 结束标记的问题,您也会遇到&lt;/script&gt; 结束标记的相同问题。一种选择是将其存储在变量中并使用它。示例:

<?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;

【讨论】:

  • 谢谢,那么我怎样才能将 javascript 添加到 PHP 的 heredoc 中?
  • @BoonGǎgǎ,一个想法是将&lt;/script&gt; 存储在一个变量中,例如$endScript = '&lt;/' . 'script&gt;';(以防万一您对'&lt;/script&gt;' 也有问题),然后使用@ 987654331@ 而不是 HEREDOC 实例中的 &lt;/script&gt;
猜你喜欢
  • 2012-02-19
  • 2016-08-24
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 2013-02-17
  • 2015-02-23
  • 2013-06-15
相关资源
最近更新 更多