Forum Moderators: coopster

Message Too Old, No Replies

Importing CSS with PHP

importing css with php

         

Tourex

4:40 pm on Aug 16, 2006 (gmt 0)

10+ Year Member



I have a PHP script that displays a small calendar/diary block. It is called by an include() statement within the code of the target page on which we want the calendar displayed. Both the calendar script and the target pages use different CSS files (with unique rule classes). The target pages are based on a common template which loads the main CSS file. We want to avoid having special templates/pages to load the calendar script CSS.

Question 1: How can I load CSS definitions in the PHP script without having to modify the header section os the target page?

Secondly, the calendar is displayed in different styles on different pages by setting a variable before the include() call. Each of the four styles uses a different CSS file.

Question 2: How can I load different CSS layouts depending upon the value of a PHP variable?

Having spent two days on various experiments and drawing a blank, I would be more than grateful to anybody who can put me straight on these two issues.

coopster

2:09 pm on Aug 22, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could just buffer (see Output Control Functions [php.net]) the HTML as opposed to sending it directly to the browser and then use str_replace() [php.net] or preg_replace() [php.net] to find the closing </head> element and replace it with another <style> (or <link>) element and closing </head> element. So basically you would be "inserting" another <style> (or <link>) element.

To load the correct CSS markup in this fashion you could just use something like a switch [php.net]. Putting it all together ...

<?php 
function callback($buffer)
{
global $css;
// update the CSS
return (str_replace("</head>", "$css\n</head>", $buffer));
}
ob_start [php.net]("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
$myPHPvariable = 'two';
switch ($myPHPvariable) {
case 'one':
$css = '<link rel="stylesheet" type="text/css" media="all" href="/css1.css" />';
break;
case 'two':
$css = '<link rel="stylesheet" type="text/css" media="all" href="/css2.css" />';
break;
case 'three':
$css = '<link rel="stylesheet" type="text/css" media="all" href="/css3.css" />';
break;
default:
$css = '<link rel="stylesheet" type="text/css" media="all" href="/default.css" />';
break;
}
ob_end_flush();
?>

I did not test this, and I peeled the sample code right out of manual before modifying it a bit. Play around and see if it will work for you.