创建包含嵌套引号的变量的字符串时出现语法错误

MTV*_*TVS 1 php string double-quotes

这个原因错误:

$xml .= "\t<team id=\"$team['id']\"";
Run Code Online (Sandbox Code Playgroud)

这不会导致错误:

$xml .= "\t<team id=\"\"";
Run Code Online (Sandbox Code Playgroud)

有什么问题?

Sal*_*n A 6

您可以删除单引号:

$xml .= "\t<team id=\"$team[id]\"";
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下语法之一在双引号字符串中使用大括号:

$xml .= "\t<team id=\"{$team['id']}\"";
$xml .= "\t<team id=\"${team['id']}\"";
Run Code Online (Sandbox Code Playgroud)

参考(向下滚动到"变量解析"部分).

几个例子:

echo "$team[id]";
echo "{$team['first name']}"; // e.g. when there are spaces in key names
echo "{${getVarName()}}";     // e.g. when we cannot use $ directly
Run Code Online (Sandbox Code Playgroud)