【问题标题】:php nested heredoc and escaping variablesphp嵌套heredoc和转义变量
【发布时间】:2018-01-07 01:42:49
【问题描述】:

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

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

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

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

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

如果我使用 \\$languageStrings 试图逃避我得到的反斜杠:

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

我怎样才能纠正这个问题,所以我得到$languageStrings = Array (?我确实考虑过尝试打开文件并插入特定的行,但文件总是不同的。

我愿意接受建议

这是我的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);

【问题讨论】:

    标签: php heredoc


    【解决方案1】:

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

    $strings = '\$languageStrings';
    

    并在 heredoc 字符串中将 \$languageStrings 替换为 $strings = Array (

    输出符合我的预期

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      <<<"FOO"
      FOO;
      

      <<<FOO
      FOO;
      

      为了便于理解,我更喜欢每次都使用双引号 heredoc,尽管它是可选的。

      文档说:php.net

      Nowdocs 之于单引号字符串,就像 heredocs 之于 双引号字符串。 nowdoc 的指定与heredoc 类似, 但是在 nowdoc 中没有进行任何解析。该结构非常适合 嵌入 PHP 代码或其他大块文本,而无需 逃脱。它与 SGML 结构有一些共同的特征,因为它声明了一个文本块,它不是 解析。

      nowdoc 使用与 heredocs 相同的

      【讨论】:

        猜你喜欢
        • 2011-07-16
        • 2015-01-28
        • 2017-11-21
        • 2018-02-24
        • 2013-06-15
        • 2015-04-21
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        相关资源
        最近更新 更多