PHP如何覆盖文件的特定部分

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

我有一个小CSS文件。

:root {
    --header-bg:
#004d73;
    --header-title-color:
#dbebfa;
}

我正在尝试编写一个接受输入值的脚本,并使用新数据覆盖CSS文件中的特定行。这是我到目前为止所拥有的。

 $path = 'custom-test.css';
 if (isset($_POST['header-bg'])) {
    $fh = fopen($path,"a+");
    $string = $_POST['header-bg'];
    fwrite($fh,$string,7); // Write information to the file
    fclose($fh); // Close the file
    header('Location: ' . $_SERVER['HTTP_REFERER']);
 }

这是有效的,当然它只是将数据附加到文件的末尾。

我无法弄清楚我是否需​​要通过fopen,fwrite指定要覆盖的行,或者如果我需要脚本将整个文件打开到一个数组中(这超出了我的基本PHP技能组)。

再一次,我的技能非常有限。我们欢迎所有提示,但扩展现有代码的建议将非常有用。

BTW没有详细说明我不能使用数据库条目。

php css templates overwrite
2个回答
-1
投票

您可以使用模板文件和str_replace函数并像这样执行。

让我们假设您有style.css,其中包含:

:root {
    --header-bg: #004d73;
    --header-title-color: #dbebfa;
}

你有template.style.css包含这个:

:root {
    --header-bg: {{background}};
    --header-title-color: {{color}};
}

现在,只要你需要更改style.css,你需要做的就是替换template.style.css中的值并将内容放在style.css

<?php 

$background = $_POST['background'];
$color      = $_POST['color'];
// you may need to check these values before using them

$contents = file_get_contents('template.style.css');
$css = str_replace('{{background}}',$background,$contents);
$css = str_replace('{{color}}',$color,$css);
file_put_contents('style.css',$css);



?>

更新

从您的评论中,我了解到您正在尝试为不同服务器中的每个网站使用不同的主题颜色,并且您不需要php。

最简单的方法是为每个网站手动更改每个文件,因为您不会再次更改它们,但是!如果你想要更动态的东西,你仍然不需要php,因为在那个原因你将需要Less.js:在你的less文件中使用2个变量(你不需要改变CSS,你只需要替换颜色通过变量名称@varName)并通过less.js为每个网站设置变量。

更新

在你的情况下,我认为第一个答案是最好的,我会留下我的第二个建议,以防有人在寻找答案或发现它在不同情况下有用。


-1
投票

最好和最标准的方法是制作模板文件,然后使用参数渲染该文件。 看看this

首先制作一个这样的模板文件:

:root {
    --header-bg: <?=$this->e($headerBg)?>;
    --header-title-color: <?=$this->e($headerTitleColor)?>;
}

在你的PHP脚本中:

 $path = './';
 $template = 'custom-test.css';
 $output = 'output-test.css';
 if (isset($_POST['header-bg'])) {
    $params = [
        'headerBg' => $_POST['header-bg'],
        'headerTitleColor' => ''
    ];
    $templates = new League\Plates\Engine($path);
    file_put_content($output, $templates->render($template, $params));
    header('Location: ' . $_SERVER['HTTP_REFERER']);
 }

您必须使用composer安装此软件包(如果您使用的是composer):

composer require league/plates

然后在您的脚本require 'vendor/autoload.php'中导入它 如果您不使用作曲家,则必须使用download it并在脚本中包含以下文件

    "src/Template/match.php",
    "src/Extension/Data/data.php",
    "src/Extension/Path/path.php",
    "src/Extension/RenderContext/func.php",
    "src/Extension/RenderContext/render-context.php",
    "src/Extension/LayoutSections/layout-sections.php",
    "src/Extension/Folders/folders.php",
    "src/Util/util.php"
© www.soinside.com 2019 - 2024. All rights reserved.