【问题标题】:PHP syntax error, unexpected 'echo' (T_ECHO)PHP 语法错误,意外的 'echo' (T_ECHO)
【发布时间】:2021-08-30 04:17:47
【问题描述】:

文件 theme-style.php 包含 PHP 代码,我正在尝试将其输出到 CSS 文件。当我尝试将echo 与file_gets_content 一起使用时,我收到错误代码 syntax error, unexpected 'echo' (T_ECHO)

如果我不使用echo 它只会将所有 PHP 代码输出到 CSS。我在哪里犯错了?

这是我正在使用的代码:-

$fp = fopen('mstyle.css', 'w');
$mee = echo file_get_contents(get_template_directory() . '/css/theme-style.php');
fwrite($fp, $mee);
fclose($fp);

【问题讨论】:

  • echo 是用于将内容直接发送到输出的命令。你不能分配回声的结果。如果要分配变量,只需分配它...无需回显。

标签: php variables echo


【解决方案1】:

你不需要回声

$fp = fopen('mstyle.css', 'w');
$mee = file_get_contents(get_template_directory() . '/css/theme-style.php');
fwrite($fp, strip_tags($mee));
fclose($fp);

file_get_contents 直接返回à字符串

https://www.php.net/manual/en/function.file-get-contents.php

并且echo不是用来分配变量而是将st发送到输出设备

strip_tags用于去除html标签,php代码在html标签内。

【讨论】:

  • 这并不能完全回答问题 - 这不会评估 theme-style.php 文件的内容,并且如问题中所述,它只会“将所有 php 代码输出到 css”
  • This answer 类似的问题应该得到给定文件的评估输出准备好传递到fwrite
  • 它只输出所有 PHP 代码。我已经在我的问题中提到了
  • 正确,但你能举一个你想要(删除)的例子
  • 该文件包含 PHP 和 css 的组合。文件的输出是唯一的 CSS。我想把它写到一个单独的 css 文件中
【解决方案2】:

使用输出缓冲区 ob_start 将解决问题并给出正确的输出。

$string = get_include_contents(get_template_directory() . '/css/theme-style.php');

function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}
$fp = fopen('mstyle.css', 'w');
fwrite($fp, $string);
fclose($fp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2017-12-13
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多