我可以在PHP内的JavaScript中编写PHP吗?
在PHP脚本中,我有这个:
Inside a PHP script I have this:
echo <<<EOD
<script type="text/javascript">
document.getElementById('my_element_id').innerHTML='Do stuff';
</script>
EOD;
我可以在JavaScript中添加PHP吗?用PHP代码替换东西"部分吗?如果是,该怎么办?
Can I add PHP inside the JavaScript? Replace the "Do stuff" part with PHP code? If yes, how do I do it?
首先,应该注意,这与javascript没有关系.您可以使用任何形式的文本.您的实际问题是如何在Heredoc内部使用变量.
First of all, it should be noted that this has nothing to do with javascript. You could have any form of text. Your actual question is how to use a variable inside of a heredoc.
此处是定义如下:
现在文档将单引号引起来的字符串,此处文档将双引号引起来的字符串.nowdoc的指定方式与Heredoc相似,但是在nowdoc内部未进行任何解析.该结构非常适合嵌入PHP代码或其他大型文本块,而无需进行转义.
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.
这意味着自此有效:
$name = 'Foo';
echo "My name is $name"; // Using double quotes so variables get expanded
然后这也可以工作:
$name = 'Foo';
echo <<<EOD
My name is <strong>$name</strong>
EOD; // Using heredoc so variables get expanded
从本质上讲是肯定的,只要您先将"要做的事情" 内容放入变量中即可.请注意,如果您使用更高级的变量/数组,则最好先执行 $ array = json_encode($ array)
,然后再将其粘贴到JS代码中(想象一下 $ name
是 The Boss's Wife
-然后,如果您不对其进行编码,则撇号会破坏您的JS).
Essentially meaning that yes, as long as you put your 'Do stuff'
content into a variable first. Note that if you use more advanced variables/arrays, it's a good idea to do a $array = json_encode($array)
before pasting it into JS code (imagine if $name
was The Boss's Wife
- then the apostrophe would ruin your JS if you don't encode it).