I know you can change the CSS by changing the stylesheet files themselves and adding a .php extension but I need to find a way of using the PHP script on the index.php page to tell the header which stylesheet to put in to action depending on what month of the year it is.
My code at the moment is accurate to the best of my knowledge but for some reason it isn't being read in and implemented with any of the stylesheets.
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$date = getdate();
$month = $date["mon"];
$style = "style.css";
$autumn = "autumn.css";
$xmas = "christmas.css";
if($month == 10)
{
echo '<link rel="stylesheet" type="text/css" href="$autumn"/>';
}
elseif($month =="12")
{
echo '<link rel="stylesheet" type="text/css" href="$xmas"/>';
}
else
{
echo '<link rel="stylesheet" type="text/css" href="$style"/>';
}
?>
</head>
Any help would be much appreciated!
You're trying to use variables inside single quotation marks ('). That does not work, variables are only interpreted inside double quotation marks ("). Therefore, your code most proabably literally outputs
<link rel="stylesheet" type="text/css" href="$autumn"/>
The necessary code line would be (adapt accordingly for the other lines, of course):
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$autumn\"/>";
Alternatively, you could replace the escaped double quotation marks inside the HTML code with single quotation marks. Browsers don't really care about that (I'm not sure about the specification).
If you want to avoid some redundancy in your code, you could try an approach like this instead:
<?php
$style = "style"; // Set the default stylesheet name
// then check for the special cases
$date = getdate();
if ($date["mon"] == 10) $style = 'autumn';
if ($date["mon"] == 12) $style = 'christmas';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="<?php echo $style; ?>.css"/>
</head>
This may also be easier to maintain than echoing out a bunch of HTML.
If you're using a HTML5 doctype you don't need the type attribute on your link element. I thought I'd throw this approach into the pile:
switch( $month ) {
case 10:
$file = 'autumn.css';
break;
case 12:
$file = 'christmas.css';
break;
default:
$file = 'style.css';
}
<link rel="stylesheet" href="<?= $file ?>">
I think you need to try:
echo '<link rel=stylesheet" type="text/css" href="'.$style.'"/>';
Related
this one may be easy, but seems a problem for my server (or me myself).
I have this piece of code in index.php:
<?php
header('Content-Type: text/html; charset="UTF-8"');
// Some code for generating data to be displayed
foreach ($ObjectArray as $SingleObject) {
print_r($SingleObject->getAllProperties());
}
And it does this:
But I don't want to use header('Content-Type: text/plain; charset="UTF-8"'); - I'd rather include HTML code from my header.htm:
<html>
<head>
<meta charset="UTF-8">
<title>Test Cards</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jquery-3.1.0.min.js"></script>
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery-ui.js"></script>
</head>
with my index.php like that:
<?php
include 'view/header.htm';
echo '<body>';
// Some code for generating data to be displayed
foreach ($ObjectArray as $SingleObject) {
print_r($SingleObject->getAllProperties());
echo '</body>';
echo '</html>';
}
Unfortunately, this ain't too good. Charset still is recognized as UTF-8, but the result is far from my expectations:
Please tell me, what is happening and how to handle this kind of problem. Is it a case of combining HTML and PHP (clean PHP does use some fancy styling when HTML ain't present?) or maybe some mistake in my code?
Thanks in advance :)
The formatted look is preserved, because in the first case you have the content-type text/plain, while in the second case it is HTML (text/html).
You can wrap it in <pre></pre> tags to preserve formatting when returning HTML.
<?php
include 'view/header.php';
echo '<body>';
echo '<pre>';
// ...
// your foreach here
// ...
echo '</pre>';
echo '</body>';
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've done a bit of research before asking this question, although i've had 0 luck.
What i'm trying to figure out is pretty much how I can make kinda of a template system. I know I could look at how others are done, but I just thought i'd ask to get a simple answer.
Pretty much I want to be able to use something like {Name} or %name% in html, which obviously comes from valuables in a PHP file.
So for example, In a PHP file I have, I have the valuable of $Name == "My Name";
Instead of putting PHP into the html which would look messy which would be <?php echo $Name; ?> I'd like to be able to use %Name% or {Name} instead.
Hopefully someone can understand what I mean, and help me out.
Thank you
just do a string replace:
public function _output($tpl, $values) {
if(!is_readable($tpl)) {
return ['err'=>'The ('.$tpl.') template is missing or unreadable!'];
}
$output = file_get_contents($tpl);
if($output === false){
return ['err'=>'Error loading template file ('.$tpl.')'];
}
foreach ($values as $key => $value) {
$tagToReplace = "[#".$key."]";
$output = str_replace($tagToReplace, $value, $output);
}
return $output;
}
usage:
_output('path/to/html/file', ['key'=>'value', 'key'=>'value'])
Here is the breakdown:
Make sure that the html template file exists and is readable
Read the template file into a string
Replace known placeholders with real values
Your html file might look like this:
<!DOCTYPE html>
<html>
<head>
<title>[#site_title]</title>
<script src="[#polymer_elements]webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="[#polymer_elements]paper-styles/paper-styles.html">
<link rel="import" href="[#polymer_elements]paper-styles/paper-styles-classes.html">
<link rel="import" href="[#polymer_elements]paper-header-panel/paper-header-panel.html">
<link rel="import" href="[#polymer_elements]paper-drawer-panel/paper-drawer-panel.html">
<link rel="import" href="[#polymer_elements]paper-toolbar/paper-toolbar.html">
<link rel="import" href="[#polymer_elements]iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="[#polymer_elements]iron-media-query/iron-media-query.html">
<link rel="import" href="[#custom_elements]universal/ajax-widgets-loader/ajax-widgets-loader.html">
<link rel="import" href="[#custom_elements]universal/ajax-app-loader/ajax-app-loader.html">
</head>
So assuming you have an array like array('polymer_elements'=>'path/to/polymer/folder/', 'site_title'=>'my site title')
Your final output from php will be like
<!DOCTYPE html>
<html>
<head>
<title>my site title</title>
<script src="path/to/polymer/folder/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="path/to/polymer/folder/paper-styles/paper-styles.html">
<link rel="import" href="path/to/polymer/folder/paper-styles/paper-styles-classes.html">
<link rel="import" href="path/to/polymer/folder/paper-header-panel/paper-header-panel.html">
<link rel="import" href="path/to/polymer/folder/paper-drawer-panel/paper-drawer-panel.html">
<link rel="import" href="path/to/polymer/folder/paper-toolbar/paper-toolbar.html">
<link rel="import" href="path/to/polymer/folder/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="path/to/polymer/folder/iron-media-query/iron-media-query.html">
<link rel="import" href="path/to/polymer/folder/universal/ajax-widgets-loader/ajax-widgets-loader.html">
<link rel="import" href="path/to/polymer/folder/universal/ajax-app-loader/ajax-app-loader.html">
</head>
NB: To all the people saying "use smarty", I think smarty and all the other template engines are good. They are developed by a larger community and not just one person, but sometimes we just need a little snippet and not a whole library.
As far as I understand, you are looking for str_replace, this will do the job of replacing the keyword with a actual value. I sometimes use it like so:
$template = file_get_contents('test.php');
$name = 'Mrs. Happy Dash.';
//Preps keywords in the template that needs to be replaced with our data.
$keywords = array
(
"{TITLE}" => 'Thank you for visiting',
"{INTRO}" => 'I hope you enjoyed your stay ' . $name,
"{SUB_INTRO}" => '<p style="color:red;">REMEMBER TO PAY!</p>',
"{ORDER_SUMMARY}" => '1x Sky diving class - 10 Euro',
"{HOWTOPAY_TITLE}" => 'You can pay like this:',
"{HOWTOPAY}" => 'Credit card',
"{FOOTER}" => 'Bye bye'
);
//Replaces the data in the template
foreach($keywords as $search => $data){
$template = str_replace($search, $data, $template);
}
echo $template;
You can practically use anything you want as keywords, %NAME%,#NAME#. As long as you write them in the keywords array.
The data you are using to replace the keywords can also contain HTML, which is useful if you want to show different styles depending on certain options / criteria.
The above example is of course very rough and can be improved in many ways but it should offer a simple and easy way to do it (and it's easy to adjust to a more personal need / taste).
What is a general way to grab all href tags using regex and preg_match_all to get the href value given the tag is not always in order.
Example:
<link href="foo.css" rel="stylesheet" type="text/css"/>
<link type="text/css" href="bar.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="bar1.css"/>
<link type="text/css" href="bar2.css" rel="stylesheet"></link>
<link href="path/foo.css" rel="stylesheet" type="text/css"/>
Should result in :
Array(
'foo.css',
'bar.css',
'bar1.css',
'bar2.css',
'path/foo.css',
)
Parsing is the way to go:
$x = file_get_contents("foo.txt");
$xml = simplexml_load_string("<links>$x</links>");
$results = array();
foreach ($xml->link as $link)
$results[] = (string)$link['href'];
see it working: https://eval.in/132898
The regex expression your looking for is something like this, but will require a bit further refinement:
<link\s+(?:[^>]*?\s+)?href="([^"]*)"
Testing against
<link href="foo.css" rel="stylesheet" type="text/css"/>
The returned value is
<link href="foo.css"
Here's a good place to test out your expressions: http://regexpal.com/
i would say:
preg_match_all('/href=\"([a-z1-9\/.]+)\"/img', $head, $matches)
I'm struggling with this. The idea is to replace all <link> tags, containing specific href attribute inside given string (which comes from a buffer and it is regular HTML, but malformed sometimes).
I've tried to use the PHP DOM approach, also the SimpleHTMLDOM parser library, so far nothing works for me (the problem is that DOM approach returns only links inside <body> element, but not those in <head> section of the page), so I decided to use regex.
Here is the non-working PHP DOM approach code:
function remove_css_links($string = "", $css_files = array()) {
$css_files = array("http://www.example.com/css/css.css?ver=2.70","style.css?ver=3.8.1");
$xml = new DOMDocument();
$xml->loadHTML($string);
$link_list = $xml->getElementsByTagName('link');
$link_list_length = $link_list->length;
//The cycle
for ($i = 0; $i < $link_list_length; $i++) {
$attributes = $link_list->item($i)->attributes;
$href = $attributes->getNamedItem('href');
if (in_array($href->value, $css_files)) {
//Remove the HTML node
}
}
$string = $xml->saveHTML();
return $string;
}
Here is the regex code, however I know that all of you do not recommend to use it for parsing of HTML, but let's not discuss this here and now:
$html_text = '
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" />
<link rel="alternate" type="application/rss+xml" title="Website » Feed" href="/feed/" />
<link rel=\'stylesheet\' href=\'http://www.example.com/css/css.css?ver=2.70\' type=\'text/css\' media=\'all\' /></head>
<body>...some content...
<link rel=\'stylesheet\' id=\'css\' href=\'style.css?ver=3.8.1\' type=\'text/css\' media=\'all\' />
</body></html>
';
$url = preg_quote("http://www.example.com/css/css.css?ver=2.70");
$pattern = "~<link([^>]+) href=".$url."/?>~";
$link = preg_replace($pattern, "", $html_text);
The problem with the regex is that the href attribute can be at any place inside <link> tag and this one, which I use, can detect any type of <link> tags, as you can see I do not want to remove the shortcut icon or alternate types of them, as well as anything different than given URL as href attribute. You can notice that the <link> tags contains different type of quotes, single and/or double.
However, I'm open to suggestions and if it is possible to make the DOM approach work, rather than use regex - it's OK.
OK, so here you are :
<?php
$html_text = '
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" />
<link rel="alternate" type="application/rss+xml" title="Website » Feed" href="/feed/" />
<link rel="stylesheet" href="http://www.example.com/css/css.css?ver=2.70" type="text/css" media="all" /></head>
<body>...some content...
<link rel="stylesheet" id="css" href="style.css?ver=3.8.1" type="text/css" media="all" />
</body></html>
';
$d = new DOMDocument();
#$d->loadHTML($html_text);
$xpath = new DOMXPath($d);
$result = $xpath->query("//link");
foreach ($result as $link)
{
$href = $link->getattribute("href");
if ($href=="whatyouwanttofilter")
{
$link->parentNode->removeChild($link);
}
}
$output= $d->saveHTML();
echo $output;
?>
Tested and working. Have fun! :-)
The general idea is :
Load your HTML into a DOMDocument
Look for link nodes, using XPath
Loop through the nodes
Depending on the node's href attribute, delete the node (actually, remove the child from its... parent - well, yep, that's the php way... lol)
After doing all the cleaning-up, re-save the HTML and get it back into a string
I need to change the CSS on a webpage based on a query string in the URL... but I'm new to PHP and havn't been able to find sufficient examples on how to do it.
Basically when a user clicks on a menu link, and is then sent to an "aboutUs.php" page, I need the CSS on the aboutUs.php page to change based on the string query.
If I understand what you want correctly:
if (isset($_GET['query'])){
$query = $_GET['query'];
}else{
$query = NULL;
}
Then something like this:
if ($query == 'x'){
echo "
<style>
Whatever style you need...
</style>
";
}elseif ($query == 'y'){
echo "
<style>
Whatever other style you need...
</style>
";
}else{
echo "
<style>
Whatever default style you need...
</style>
";
}
Of course you can echo stylesheet link instead of style tags, but the logic is the same.
You can change your style.css to style.php which you can load in the page as a style sheet.
You need to include a header type in your php file:
<?php
header("Content-type: text/css");
?>
and then generate the content dynamically.
In hope I didn't missunderstand the question. This can help you change the content of the css file.
If you have multiple css files and you want to import one of them depending on the parameters to aboutus.php, that's a different story.
In the head of your program (where you would include the css stylesheets) do a simple if else:
if (isset($REQUEST['query_string'])) {?>
stylesheet link
<?php } else { ?>
stylesheet link 2
<?php } ?>
You can save the selected CSS into a cookie:
if (isset($_GET['setstyle'])) {
setcookie('style', $_GET['setstyle'], time()+60*60*24*30, '/');
}
The Style can then be read like this: $_COOKIE['style'].
http://example.com/?setstyle=black -> Style is set to „black“
not very pretty solution but for example something like this would work
<? php
if($str=="main"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/main.css" />'
}
else if($str=="other"){
echo '<link rel="stylesheet" type="text/css" media="all" href="/css/other.css" />'
}
?>
be careful with doing something like:
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
it is not very secure way, unless you do for example an array with possible values, something like
$possibleCss = array("main", "other");
if(in_array($str, $possibleCss){
<link rel="stylesheet" type="text/css" media="all" href="/css/$str.css" />
}
You need to create a php file with header text/css, this file you can call with get parameters.
example:
$style = $_GET["style"];
header("Content-type: text/css");
if($style=="blue")
echo ".class{background-color:blue;}";
else
echo ".class{background-color:white;}";
Call the css with get parameters
<link rel="stylesheet" type="text/css" href="style_file.php?style=blue" />
Knowing the purpose of your question, from here, I would put all of your common css in on stylesheet, and simply call out specific display properties for the elements you care about. Make all of your elements display: none in your main stylesheet.
<link type="text/css" rel="stylesheet" href="mainStyleSheet.css" />
<style type="text/css">
<?php
if (isset($_GET['section'])){
// Sanitize
$section = preg_replace('/[^a-zA-Z]/', $_GET['section']);
echo '#' . $section . ' { display: block; }';
}
?>
</style>
In this case, section is a parameter, set to ourMisson, ourHistory, etc., called like this:
http://beta.***.com/aboutUs.php?section=ourMission