I want to include a php script in a css file:
<?php
$str = "5px";
echo $str;
?>
and then
.header {
font-size: $str;
}
Is it possible?
No, not like that. CSS isn't a programming language, and has NOTHING to do with PHP.
You can, however, have PHP generate the CSS:
html:
<link rel="stylesheet" href="foo.php" ... />
foo.php
<?php
header('Content-type: text/css');
$str = '5px';
?>
.header {
font-size: '<?php echo $str; ?>';
}
Note that since you'r GENERATING css, you have to make absolutely SURE that whatever PHP outputs will be valid for the context the output is going into. It is very easy to output something that'll be a CSS syntax error and kill the rest of the CSS file.
Related
I have created a skin switcher and it is working great, but the code is messy.
I save a cookie and then for some defined css classes, I append '-userDelectedColourFromTheCookie' to the end of the css class to apply it on the page.
So far, I am adding a short php line to the end of every instance of these classes in the html code and as I have said, it is working.
I would prefer to run the php code just once across the whole page and update all occurrences of an array containing the required classes to append the class as above.
I have this at the top of my page:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc
I am defining an array of css classes, then reading the user colour from the cookie and appending it to the css class.
As and example, the default class might be 'theme-3' but of the user selects the blue skin, then this class becomes 'theme-3-blue' and so on.
But it's not working.
Any help would be appreciated.
Don't mess with the element class lists. Use CSS files to apply the colours you want.
Start with a basic CSS design file:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}
Then create CSS colour files with different colour selections:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}
red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}
default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}
Then load the colour theme you want
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}
Then echo $themeCSS in your <head> just like any other <head> element
** I've used standard HTML elements here to illustrate, but any CSS selectors should work.
I believe you want to change the class names inside the $classList variable by appending the selected color theme from the cookies.
You may use the array_map function to modify all elements of your $classList array.
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);
Once you use the array_map function, all elements of the $classList array will be appended with the "-blue".
You can execute and see the output here
http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
Several good ways to do it. It's a little more complicated with the array of classes but you should be able to adjust this if you need it (not sure why the syntax highlighting is wonky).
Use output buffering and replace at the end:
<?php
ob_start();
?>
<html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html>
<?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}
With the array of classes, just do it the same way with output buffering but replace like so:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());
I am trying to insert a shortcode inside CSS file but i am unable to achieve it. Don't know where I am going wrong.
I am inserting below code inside my style.css file:
div#cuzd-dispatch-general-v {
display: <?php echo do_shortcode('[dispatch_date_hide]'); ?> ;
}
OUTPUT:
div#cuzd-dispatch-general-v {
display: <?php echo do_shortcode('[dispatch_date_hide]');
}
Output as Image: http://oi61.tinypic.com/2uiyd4x.jpg
add this code in your header.php inside <style> </style>
div#cuzd-dispatch-general-v {
display: <?php echo do_shortcode('[dispatch_date_hide]'); ?> ;
}
PHP code cannot be interpreted inside a .css file so your php code will be showen as a plain text, add the part of your code in the style tag of your php file.
I have a variable with a score and I'm having php change the color of a div element based on this variable. This if statement is always resolving to True. Anyone see the flaw?
<style>
.poster{
background-color:<?php
if($voteRating > 80.0){
echo "#2ecc71;";
}
else{
echo "#f1c42c;";
}
?>
}
.year{
color:;
}
</style>
Personally, I would create two CSS classes and echo an appropriate class name on the element instead.
if($voteRating < 80)
{
echo "<div class='one-class'>";
}
else
{
echo "<div class='another-class'>";
}
Or, considering this is more of front-end thing, maybe use ajax to determine the $voteRating and then change the style with javascript. Just some alternatives.
Nothing wrong with code. Try echoing $voteRanking to see if it gives more then 80.0
try something like this:-
<style>
.poster{
background-color:<?php echo ($voteRating > ceil(80.0)) ? "#2ecc71;" : "#f1c42c;"; ?>
}
.year{
color:;
}
</style>
You should create different classes for each color and then use javascript or php conditions to set the class upon page rendering or any other event triggering. This way its easy to debug issues with your code.
for example
<style>
.posterhigh{
background: #2ecc71;
}
.posterlow {
background: #f1c42c;
}
</style>
I have several sites on the same hosting package. They’re all in different directories. ( i.e. “htdocs/site1”). I want to be able to have them all share one CSS file.
I was wondering if there is a way to change the color of certain elements based on which directory the site is in.
Ideally I would like to be able to define what directory the page is in and what color to use for each directory. Then in my CSS do something like:
.button { color: <?php echo $color ?> ;}
to each element that gets a color change.
Is this possible and if so, how do I go about setting this up?
thank you
You could add different classes to your body tag depending on the directory:
<body class="<?php echo $dir; ?>">
where the $dir variable is given a different value (let's say $dir = 'site1',...) for each directory...
... And then have something like:
.site1 #button { /*styles*/ }
.site2 #button { /*styles*/ }
.site3 #button { /*styles*/ }
in your CSS file.
You could add a CSS class to the body tag of the HTML document to determine the site. In PHP you would have to find a way to write the correct site into to the document. Do you use some kind of global template?
Just to give you an idea:
PHP:
<?php
// some code
// some logic to determine which site you are on - let's say ...
$site = 'SITE1';
?><body class="<?php echo $site; ?>"><?php
// more code
?>
CSS:
body.SITE1 #button { color: #ff0000; }
body.SITE2 #button { color: #0000ff; }
body.SITE2 #button { color: #123456; }
You could dynamically generate the css file using php, where you'd have
<?php
switch ($_SERVER['SERVER_NAME']) {
case 'www.site1.com':
$color = '#ff0000';
break;
case 'www.site2.com':
$color = '...';
break;
...
default:
$color = '...';
?>
.someclass { color : <?php echo $color ?>; }
This is somewhat inefficient, however. You'd be building a css file just to change a single color each time. Better way is to simply embed the color change in the page's header as an in-line style. That way you don't have to mess with making your server parse CSS files as if they were PHP scripts, and you can put the site-specific css overrides into that inline style in the site's header.
Honestly, I would suggest you add a class to your html tag:
<html class="site1">
And within your CSS, define your css:
.site1 * .button1{ background:#f00;}
.site2 * .button1{ background:#f0f;}
.site3 * .button1{ background:#ff0;}
You can find some more information on this subject here for a PHP approach.
Im new to PHP and I can't figure out what the rules are for using the echo function. For example, if I need to echo a large block of css/js, do I need to add echo to each line of text or is there a way to echo a large block of code with a single echo?
When I try to echo a big block of code like this one, I get an error:
if (is_single()) {
echo '<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>';
}else {
}
Is there a better way to echo large blocks of code without a lot of work (adding echo to each line for example)?
Heredoc syntax can be very useful:
// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
in here is your string
it has the same variable substitution rules
as a double quoted string.
when you end it, put the indicator word at the
start of the line (no spaces before it)
and put a semicolon after it
EOT;
One option is to get out of the php block and just write HTML.
With your code, after the opening curly brace of your if statement, end the PHP:
if (is_single()) { ?>
Then remove the echo ' and the ';
After all your html and css, before the closing }, write:
<? } else {
If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.
Check out heredoc. Example:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
The is also nowdoc but no parsing is done inside the block.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).
The error in your code is caused by the unescaped single quotes which appear in the string.
See this line:
$('input_6').hint('ex: myname#example.com');
You'd need to escape those single quotes in a PHP string whether it's a single line or not.
There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>
<?php
}else {
}
Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.
Man, PHP is not perl!
PHP can just escape from HTML :)
http://www.php.net/manual/en/language.basic-syntax.phpmode.php
if (is_single()) {
//now we just close PHP tag
?>
</style>
<script>
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>
I wonder why such many people stuck to ugly heredoc.
Your problem is actually caused by:
$('input_6').hint('ex: myname#example.com');
You need to escape the single quotes to be \'
However: Using a Heredoc is a much better idea, as it will be much cleaner overall.
To expand on #hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:
<?php if (is_single()): ?>
<p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
<p>This will be shown otherwise.</p>
<?php endif; ?>
Just break out where you need to.
<html>
(html code)
<?php
(php code)
?>
(html code)
</html>
Do not use shortened-form. <? conflicts with XML and is disabled by default on most servers.
I prefer to concatenate multiple Strings together. This works either for echo AND for variables.
Also some IDEs auto-initialize new lines if you hit enter.
This Syntax also generate small output because there are much less whitespaces in the strings.
echo ''
.'one {'
.' color: red;'
.'}'
;
$foo = ''
.'<h1>' . $bar . '</h1>' // insert value of bar
.$bar // insert value of bar again
."<p>$bar</p>" // and again
."<p>You can also use Double-Quoted \t Strings for single lines. \n To use Escape Sequences.</p>"
// also you can insert comments in middle, which aren't in the string.
.'<p>Or to insert Escape Sequences in middle '."\n".' of a string</p>'
;
Normally i start with an empty string and then append bit by bit to it:
$foo = '';
$foo .= 'function sayHello()'
.' alert( "Hello" );'
."}\n";
$foo .= 'function sum( a , b )'
.'{'
.' return a + b ;'
."}\n";
(Please stop Posts like "uh. You answer to an five jears old Question." Why not? There are much people searching for an answer. And what's wrong to use five year old ideas? If they don't find "their" solution they would open a new Question. Then the first five answers are only "use the search function before you ask!" So. I give you another solution to solve problems like this.)
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
You can achieve that by printing your string like:
<?php $string ='here is your string.'; print_r($string); ?>