在 echo 语句中混合 html 和 php 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11271501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:09:22  来源:igfitidea点击:

Mixing html and php variables inside an echo statement

phphtml

提问by Steve Patterson

This may be a problem of my trouble with using single and double quotes in one statement. But I have this piece of code:

这可能是我在一个语句中使用单引号和双引号时遇到的问题。但我有这段代码:

echo '<form>
      <input type="submit" value="$number" onClick="function();">
      </form>'

The problem with this is that the submit button says the phrase $numberinstead of the value of that variable.

问题在于提交按钮显示的是短语$number而不是该变量的值。

So I looked around and found this solution:

所以我环顾四周,找到了这个解决方案:

echo "<form>
      <input type='submit' value='$number' onClick='function();'>
      </form>

This outputs the value of $number correctly, but I am used to using single quotes around my echo statements and would like to keep it that way. Why does just switching all single quotes into doubles, and doubles into singles fix the problem? And is there a modification to the first bit of code that would allow me to keep the single quotes on echo, and double quotes on the attributes?

这将正确输出 $number 的值,但我习惯于在我的 echo 语句周围使用单引号并希望保持这种方式。为什么只是将所有单引号切换为双引号,然后将双引号切换为单引号即可解决问题?是否对代码的第一位进行了修改,允许我在 echo 上保留单引号,并在属性上保留双引号?

回答by C0deH4cker

In PHP, double quoted strings are automatically parsed for any variables contained within, but single quoted strings are not. Therefore:

在 PHP 中,双引号字符串会自动解析其中包含的任何变量,但单引号字符串不会。所以:

$myVar = 21;
echo "myVar: $myVar"

This outputs the text: myVar: 21

这将输出文本: myVar: 21

Whereas:

然而:

$myVar = 21;
echo 'myVar: $myVar'

This outputs the text: myVar: $myVar

这将输出文本: myVar: $myVar

One problem with your code is that in HTML, the values of elements' attributes must be enclosed in double quotes, not single quotes. I know that some browsers will accept this form (or even no quotes at all), but this is not the correct method.

您的代码的一个问题是,在 HTML 中,元素的属性值必须用双引号括起来,而不是用单引号括起来。我知道有些浏览器会接受这种形式(甚至根本不接受引号),但这不是正确的方法。

There are various ways of achieving what you wish, correctly.

有多种方法可以正确地实现您的愿望。

Method one: Escaping double-quoted strings:

方法一:转义双引号字符串:

$myVar = 21;
echo "<div id=\"$myVar\"></div>";

While this may be a rather inelegant solution, it will work.

虽然这可能是一个相当不雅的解决方案,但它会奏效。

Method two: Using string concatenation with single (or double) quoted strings:

方法二:使用单(或双)引号字符串连接字符串:

$myVar = 21;
echo '<div id="' . $myVar . '"></div>';

This offers a better solution IMO because you can use function calls or any other PHP code in there if you wish.

这提供了更好的解决方案 IMO,因为如果您愿意,您可以在其中使用函数调用或任何其他 PHP 代码。

WARNING:

警告:

Please note that when you aren't certain of the contents of $myVar(i.e. the user enters it in), putting it directly into HTML code is a security vulnerability in the form of cross-site scripting (XSS). Imagine the user enters something like this:

请注意,当您不确定$myVar(即用户输入)的内容时,将其直接放入 HTML 代码中是跨站脚本(XSS)形式的安全漏洞。想象一下,用户输入如下内容:

lol"><script>alert('XSS!');</script></div><div id="lol2

This will cause the resulting HTML code to contain the following:

这将导致生成的 HTML 代码包含以下内容:

<div id="lol"><script>alert('XSS!');</script></div><div id="lol2"></div>

This is just a benign example, but an attacker could easily use the same technique to steal a user's cookies (to pretend to be logged in as that user). The message here is that when you aren't 100% sure of the contents of a variable, don't insert it into HTML code directly. Instead, call htmlspecialchars($myVar). This would translate to the following:

这只是一个良性示例,但攻击者可以轻松使用相同的技术来窃取用户的 cookie(假装以该用户身份登录)。这里的信息是,当您不能 100% 确定变量的内容时,不要将其直接插入 HTML 代码中。相反,调用htmlspecialchars($myVar). 这将转化为以下内容:

$myVar = $_POST['whatever'];
echo '<div id="' . htmlspecialchars($myVar) . '"></div>';

回答by David Cheung

In PHP, variables inside double quotes are processed and evaluated, while in single quotes everything is considered as part of the string.

在 PHP 中,处理和评估双引号内的变量,而在单引号中,所有内容都被视为字符串的一部分。

A better explanation here: http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm

这里有更好的解释:http: //www.trans4mind.com/personal_development/phpTutorial/quotes.htm

double quote example from the above link:

来自上述链接的双引号示例:

$something="Oh something";
echo "My answer is $something.<br>";
//result is: My answer is Oh something

single quote example from the above link:

来自上述链接的单引号示例:

echo 'My answer is $something.<br>';
//result is: My answer is $something.

回答by Sablefoste

When you use the single quote, everything inside is taken literally, except single quotes. When using double quotes, anything starting with a dollar sign ($) is assumed to be a variable by PHP. When using variables, I usually like to start the echo with a double quote.

当您使用单引号时,除了单引号之外,里面的所有内容都是按字面意思理解的。使用双引号时,任何以美元符号 ($) 开头的东西都被 PHP 假定为变量。使用变量时,我通常喜欢用双引号开始 echo。

回答by Bob Davies

If you want to keep using single quotes, you'll need to use the append operator (a period).

如果您想继续使用单引号,则需要使用附加运算符(句点)。

echo '<form>
      <input type="submit" value="' . $number . '" onClick="function();">
      </form>';

回答by ratiorick

You could just do this and avoid the whole song and dance. I think it is easier to read.

你可以这样做,避免整个歌曲和舞蹈。我认为它更容易阅读。

<form>
    <input type="submit" value="<?php echo $number; ?>" onClick="myFunction()">
</form>

回答by Arlan T

This outputs same to me

这对我来说输出相同

    echo '<link rel="apple-touch-icon-precomposed" sizes="57x57" href='. ${base_url_favicon} . '/apple-touch-icon-57x57.png />'."\n";
echo "<link rel='apple-touch-icon-precomposed' sizes='57x57' href='${base_url_favicon}/apple-touch-icon-57x57.png' />\n";

回答by Endophage

PHP differentiates between single and double quoted strings as being different things. Single quoted strings are literals, you want them output as is. Double quoted strings are to be interpreted (scanned) for any PHP variables and the appropriate replacements made.

PHP 区分单引号和双引号字符串是不同的东西。单引号字符串是文字,您希望它们按原样输出。双引号字符串将被解释(扫描)任何 PHP 变量并进行适当的替换。

This is simply a feature (and a useful one) of the language. I would actually recommend that you get used to using double quotes for strings in all languages. There is no language where it is unacceptable and in staticly typed languages (C, C++, Java, ...) single quotes indicate a character while double quotes indicate a string. That is, String foo = 'my string';would error in Java as would char * foo = 'my string';in C or C++. However, char foo = 'a';is valid, as is String foo = "my string";

这只是该语言的一个特性(也是一个有用的特性)。我实际上建议您习惯于对所有语言的字符串使用双引号。没有任何语言是不可接受的,并且在静态类型语言(C、C++、Java 等)中,单引号表示一个字符,而双引号表示一个字符串。也就是说,String foo = 'my string';在 Java 中会像char * foo = 'my string';在 C 或 C++ 中一样出错。但是,char foo = 'a';是有效的,原样String foo = "my string";

Only if you need to eke out the last nanoseconds of performance from PHP might you go through and convert double quoted strings to single quoted strings. In other languages it doesn't matter. Afaik, PHP is the only language that make this string specific double vs. single quotes distinction.

只有当您需要从 PHP 中获得最后几纳秒的性能时,您才可能经历并将双引号字符串转换为单引号字符串。在其他语言中,这无关紧要。Afaik,PHP 是唯一一种使此字符串特定于双引号和单引号的语言。

回答by Andrew

PHP performs what is called variable interpolation on double-quoted strings, which means that the strings are searched for any variables that they might contain, whose values are substituted in the string. If you want to keep the single quotes, you will need to concatenate your strings and variables together like so:

PHP 对双引号字符串执行所谓的变量插值,这意味着搜索字符串以查找它们可能包含的任何变量,其值在字符串中被替换。如果要保留单引号,则需要将字符串和变量连接在一起,如下所示:

echo '<form>
<input type="submit" value="' . $number . '" onClick="function();">
</form>';

Or, if you want to keep the double quotes, you can escape the double quotes that you want to print:

或者,如果要保留双引号,可以转义要打印的双引号:

echo "<form>
<input type=\"submit\" value=\"$number\" onClick=\"function();\">
</form>"