php嵌套heredoc和转义变量

问题描述 投票:0回答:2

我正在使用heredoc创建一个php文件,需要在生成的文件中使用heredoc,因为该文件将创建其他文件。

<<<EOD位工作正常,我可以看到所有变量正确转义。

我遇到的问题是嵌套的heredoc <<<EOL,其中\$languageStrings没有被转义

如果我使用\$languageStrings并运行生成的文件ddd.php,则输出如下:

<?php
 = Array (
    'LBL_LOCATION_INFORMATION' => 'Basic Information',
    'LBL_CUSTOM_INFORMATION' => 'Custom Information',
    'SINGLE_' => ''
);

如果我使用qazxsw poi试图逃避我得到的反斜杠:

\\$languageStrings

我怎么能纠正这个,所以我得到<?php \ = Array ( 'LBL_LOCATION_INFORMATION' => 'Basic Information', 'LBL_CUSTOM_INFORMATION' => 'Custom Information', 'SINGLE_' => '' ); ?我确实考虑过尝试打开文件并插入特定行,但文件将始终不同。

我愿意接受建议

这是我的heredoc的一个例子

$languageStrings = Array (
php heredoc
2个回答
0
投票

我通过在heredoc之外创建一个变量来修复它

$text = <<<EOD
This is some text
This is some more text

This is a \$variable //outputs this is a $variable

This is some more text
EOD;

$text .= <<<EOD
\n
\$targetpath = 'modules/' . \$moduleInstance->name;

if (!is_file(\$targetpath)) {
    mkdir(\$targetpath);
    mkdir(\$targetpath . '/language');
    // create the language file
    \$languagepath = 'languages/en_us';

    \$languageContents = <<<EOL
<?php
\$languageStrings = Array (
    'LBL_LOCATION_INFORMATION' => 'Basic Information',
    'LBL_CUSTOM_INFORMATION' => 'Custom Information',
    'SINGLE_\$moduleInstance->name' => '\$moduleInstance->name'
);
EOL;

    file_put_contents(\$languagepath . '/' . \$module->name . '.php', \$languageContents);
}
EOD;

file_put_contents('ddd.php', $text);

并用heredoc字符串中的$strings = '\$languageStrings'; 替换\$languageStrings

输出是我的预期


0
投票

需要像Heredoc这样的单引号。这个名字是Nowdoc。 Nowdocs是单引号字符串,heredocs是双引号字符串。

$strings = Array (

要么

$foo = "bar";
echo <<<STR
str $foo
STR;

echo <<<'STR'
str $foo
STR;

预期结果: - > str bar - > str $ foo

从PHP 5.3.0开始,开放的Heredoc标识符可以选择是双引号

echo "str $foo";
echo 'str $foo';

与...一样

<<<"FOO"
FOO;

我更喜欢每次双引号heredoc用于清晰度,尽管它是可选的。

Doc说:<<<FOO FOO;

Nowdocs是单引号字符串,heredocs是双引号字符串。类似于heredoc指定了nowdoc,但是在nowdoc内部没有进行解析。该构造非常适合嵌入PHP代码或其他大块文本而无需转义。它与SGML构造共享一些共同的特性,因为它声明了一个不用于解析的文本块。

nowdoc用与用于heredocs相同的<<<序列标识,但是后面的标识符用单引号括起来,例如, <<< 'EOT'。 heredoc标识符的所有规则也适用于nowdoc标识符,尤其是关于结束标识符外观的标识符。

© www.soinside.com 2019 - 2024. All rights reserved.