如果请求某个页面,则使用 php 导入样式表

Import stylesheet with php if a certain page is requested

我想根据 php 条件(或其他)在页面中导入 css 样式表,该条件基于域 URL.

例如,如果加载的页面是 "mydomain.com/about-us",则导入一个 "css/about-us.css" 文件。

我已经尝试使用此代码,但它不起作用。

<?php
    $url = $_SERVER['REQUEST_URI'];
    if (strstr($url, "mydomain.com/about-us/")) {
        include '/css/about-us.css'; 
    }
?>

如何有条件地导入或使用 <style> 标签?

解正确:

正确的解决方案是仅使用页面名称,因此如果您的页面是 mydomain。com/about-us/

仅使用“/about-us/”。

现在还有其他问题,使用发布的代码您可以为特定页面导入 css,但我注意到如果域是 mydomain.com/about-us/team.html 中的示例页面 team.html 还加载 "about-us" 的 css 如何仅在页面 mydomain/about-us/ 中加载关于我们的 css ??

您可以将样式表添加到带有 PHP 的页面,方法是将其包含在 html 文档的 <head> 中:

<?php
echo '<link rel="stylesheet" type="text/css" href="' . $file . '">';
?>

其中 $file 是 css 文件的名称。您将必须提供更多关于您要做什么的信息以获得更好的答案。

更新

变量$_SERVER[REQUEST_URI]只给出请求的页面,而不是整个域。来自 PHP 手册,

'REQUEST_URI' The URI which was given in order to access this page; for instance, '/index.html'.

所以代码应该如下所示:

<?php
    $requested_page = $_SERVER['REQUEST_URI'];
    if ($requested_page === "/about-us" || $requested_page === "/about-us/") {
        echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
    }
?>

这将测试请求的页面是否为“/about-us”(客户端正在请求 "about-us" 页面),如果是,样式表的 link 将被回显。

使用这个:

<?php
    $url = $_SERVER['REQUEST_URI'];
    if (strstr($url, "mydomain.com/about-us/")) 
    {
        // output an HTML css link in the page
        echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css" />'; 
    }
   else
   {
        // output an HTML css link in the page
        echo '<link rel="stylesheet" type="text/css" href="/css/another.css" />'; 
   }
?>

您也可以这样做以直接导入 css 内容,但可能某些 media/images 链接会损坏:

<?php
    $url = $_SERVER['REQUEST_URI'];
    if (strstr($url, "mydomain.com/about-us/")) 
    {
        // output css directly in the page
        echo '<style type="text/css">' .file_get_contents('./css/about-us.css').'</style>'; 
    }
   else
   {
        // output css directly in the page
        echo '<style type="text/css">' .file_get_contents('./css/another.css').'</style>'; 
   }
?>

如何读取 herestrstr 将 return 字符串或 FALSE。您可以这样更改它:

<!DOCTYPE html>
<head>
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
} ?>
</head>
...
</body>
</html>

或:

<!DOCTYPE html>
<head>
<style type="text/css">
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo file_get_contents('/css/about-us.css');
} ?>
</style>
</head>
...
</body>
</html>

在第一个示例中,您的 CSS 是通过 <link> 标记包含的,在第二个示例中,PHP-脚本将您的 CSS 文件加载到 script-标签。您不能使用 include,因为它会加载另一个 php 文件并在包含它的地方执行。您应该使用我的第一个示例,因为它对服务器更友好,因为不需要读取 CSS 文件。您的页面会更快。