Is there any already done php class that could parse a link like Facebook, Google+ or Digg does? To get the title, some text and images from the page? :)
Thanks
Here is some code I pinched from sitepoint.com. I have used it a few times and it seems to work nicely...
<?php
define( 'LINK_LIMIT', 30 );
define( 'LINK_FORMAT', '%s' );
function parse_links ( $m ){
$href = $name = html_entity_decode($m[0]);
if ( strpos( $href, '://' ) === false ) {
$href = 'http://' . $href;
}
if( strlen($name) > LINK_LIMIT ) {
$k = ( LINK_LIMIT - 3 ) >> 1;
$name = substr( $name, 0, $k ) . '...' . substr( $name, -$k );
}
return sprintf( LINK_FORMAT, htmlentities($href), htmlentities($name) );
}
$s = 'Here is a text - www.ellehauge.net - it has some links with e.g. comma, www.one.com,in it. Some links look like this: http://mail.google.com - mostly they end with aspace or carriage return www.unis.no<br /> - but they may also end with a period: http://ellehauge.net. You may even putthe links in brackets (www.skred-svalbard.no) (http://one.com).From time to time, links use a secure protocol like https://gmail.com |This.one.is.a.trick. Sub-domaines: http://test.ellehauge.net |www.test.ellehauge.net | Files: www.unis.no/photo.jpg |Vars: www.unis.no?one=1&~two=2 | No.: www.unis2_check.no/doc_under_score.php |www3.one.com | another tricky one:http://ellehauge.net/cv_by_id.php?id%5B%5D=105&id%5B%5D=6&id%5B%5D=100';
$reg = '~((?:https?://|www\d*\.)\S+[-\w+&##/%=\~|])~';
print preg_replace_callback( $reg, 'parse_links', $s );
?>
This looks like something you could use:
http://www.redsunsoft.com/2011/01/parse-link-like-facebook-with-jquery-and-php/
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;
}
.img
{
float:left; width:150px; margin-right:10px;
text-align:center;
}
#linkbox
{
border:solid 2px #dedede; min-height:50px; padding:15px;
display:none;
}</style>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var content=$(this).val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
$("#linkbox").slideDown('show');
$("#linkbox").html("<img src='link_loader.gif'>");
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// Loading <title></title>data
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];
// Loading first .png image src='' data
var logo=(/src='(.*?).png'/m).exec(response)[1];
$("#linkbox").html("<img src='"+logo+".png' class='img'/><div><b>"+title+"</b><br/>"+url)
});
}
return false;
});
});
//HTML Code
<textarea id="contentbox"></textarea>
<div id="linkbox"></div>
</script>
urlget.php
<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);
}
?>
source
Related
I'm trying to return css build with multiple variables in my Wordpress website, its kind of working but it's only returning the first array. If i echo instead of return inside the foreach it shows the code correctly but outside the correct location.
Sorry for the bad code and possible definitions about php. I have only just started to learn php.
The code
function child_custom_color_css4() {
function child_custom_color_css2() {
function test_loop_1_beta() {
$boo = 'soortverhaal0 ';
$foo = 'soortverhaal1 ';
return array($boo, $foo);
}
$loops = test_loop_1_beta();
global $nectar_options;
$Styled=array();
foreach ($loops as $loop) {
return '
#test-loop.'. $loop .' {
background-color: '.esc_attr($nectar_options["accent-color"]).' !important;
}
';
}
return implode($Styled);
}
$get_arrays = child_custom_color_css2();
wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20); '''
Output:
<style id="main-styles-inline-css" type="text/css">
#test-loop.soortverhaal0 {
background-color: #f04e23 !important;
}
</style>
Edit: what need:
<style id="main-styles-inline-css" type="text/css">
#test-loop.soortverhaal0 {
background-color: #f04e23 !important;
}
#test-loop.soortverhaal1 {
background-color: #f04e23 !important;
}
</style>
I think you could do something like that:
function child_custom_color_css4() {
function child_custom_color_css2() {
$loops = [
'soortverhaal0 ',
'soortverhaal0 ',
];
global $nectar_options;
$styled = [];
foreach ($loops as $loop) {
$styled[] = '#test-loop.' . $loop . ' { background-color: ' . esc_attr( $nectar_options['accent-color'] ) . ' !important; }';
};
return implode("\n",$styled);
}
$get_arrays = child_custom_color_css2();
wp_add_inline_style( 'main-styles', $get_arrays);
}
add_action('wp_enqueue_scripts','child_custom_color_css4', 20);
I do an array push to acumulate each loop into $style array.
I think you would need to define other separator for the implode function like:
return implode("\n",$styled)
I have created a simple CSS editing/optimizing system in a WordPress plugin. Basically, the CSS files are stored in a folder. They are accessed to edit though a selection box using jQuery.
HTML
# edit stylesheet
echo '<div id="editStyles" class="s8w-hide">';
echo '<h2>Edit a Stylesheet</h2>';
echo '<form action="" method="post">';
# file name
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<select id="getStylesheeteEdit" name="filename" class="s8w-expand">';
echo '<option value="">Select Stylesheet to Edit</option>';
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$filename = basename($file);
echo '<option value="'.$filename.'">'.$filename.'</option>';
}
echo '</select>';
echo '</div>';
echo '</div>';
# styles
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<textarea id="showEditStyles" name="styles" class="s8w-expand" style="height: 350px;"></textarea>';
echo '</div>';
echo '</div>';
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12 s8w-center">';
echo '<input type="submit" name="edit_stylesheet" class="s8w navy tiny-radius" value="Edit this Stylesheet">';
echo '</div>';
echo '</div>';
echo '</form>';
jQuery
This jQuery added slashes so I added the commented out line but it did not remove them.
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
parsing php
I added stripslashes here which did remove the slashes.
/* EDIT STYLESHEET
--------------------------------------------------------- */
if(array_key_exists('edit_stylesheet',$_POST)){
$filename = $_POST['filename'];
$styles = stripslashes($_POST['styles']);
# update styles
file_put_contents(S8W_CSS_GEN . 'common/'.$filename, $styles);
# parse stylesheets
$msg = 'The stylesheet: '.$filename.' and the S8W Stylesheet have been updated.';
parseStyles($msg);
}
parseStyles($msg); minimizes and writes single style sheet.
<?php
function parseStyles($msg){
/* admin styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'admin/*.css') as $file) {
$admin_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$admin_styles .= $prep_styles;
}
/* common styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$common_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$common_styles .= $prep_styles;
}
# write admin styles
$admin_styles = $common_styles.$admin_styles;
file_put_contents(S8W_CSS . 's8w-admin-styles.css', $admin_styles);
# write admin styles
$admin_readable = $common_code.$admin_code;
file_put_contents(S8W_CSS_GEN . 'readable-admin.css', $admin_readable);
$common_styles = $common_styles;
# write admin styles
file_put_contents(S8W_CSS . 's8w-styles.css', $common_styles);
# write admin styles
$common_readable = $common_code;
file_put_contents(S8W_CSS_GEN . 'readable.css', $common_readable);
echo '<Script language="javascript">alert("'.$msg.'");</script>';
}
All of this code works great if the styles do not have double quote. The file is called to the editing textarea and parses perfectly and write the minimized file. However, if the styles have double quotes:
CSS Example with Double Quotes
/* BUTTONS
------------------------------------------------------------------- */
button.s8w,
a.button.s8w,
input[type="submit"].s8w,
input[type="button"].s8w {
position:relative;
top:0;
left:0;
padding:10px 15px;
line-height:100%;
vertical-align: middle;
cursor: pointer;
overflow:visible;
font-weight:normal;
font-size:16px;
text-decoration:none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display:inline-block;
zoom:1;
background: #fcfcfc;
color:#666;
border:1px solid #cccccc;
text-align: center;
border-radius: 0;
}
The file will save and be minimized. But when the file is called though jQuery, though the edits are saved to the file, the new edits do not render in the textarea and as a result are lost if the file is saved once again. Hope I was able to explain the problem clearly. Any help or thoughts are appreciated.
While I am still not sure what was happening, the problem was in this jQuery:
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
When a css file was edited the edits would be saved and parsed through the minimizer php, but the above jQuery would not pick up the edits on the saved file when it was reselected. Have no idea as to why?
I was able to resolve the issue by changing the jQuery to:
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var url = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/get-stylsheet.php';
var postit = $.post( url, {which:which});
postit.done(function( data ) {$('#showEditStyles').val(data);});
});
and adding a php parse file with only one line of code to be able to make use of file_get_contents() instead using jQuery to get the contents of the desired css file:
<?php
$file = 'common/'.$_POST['which']; echo file_get_contents($file);
I want to select all less code from a file .But i can not find the right way to do it.
This is my code so far
$d = <<<EOT
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
EOT;
$pattern = '/.*\{(?s:.*?)\}$/mi';
$t = preg_match_all($pattern, $d, $out, PREG_PATTERN_ORDER);
foreach ($out[0] as $key) {
echo '<br><pre>'.$key."</pre>";
}
And this is the result:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
For the first 2 classes is ok but last one is not ok because they are missing 2 other }.
How can i fix it?
It looks like you want to match individual blocks, so a recursive pattern will return balanced braces. As stated in comments under the question, this method may break when character anomalies occur. I believe there are css parsers out "in the wild" but I don't have any to recommend.
Code: (Demo)
if (preg_match_all('~.*\{((?R)|[^}])*}~', $d, $out)) {
echo implode("\n---\n",$out[0]);
}
Output:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
---
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
---
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
If you don't need to separate the blocks, you can modify the pattern like this:
~[^{]*\{((?R)|[^}])*}~
But then it depends on what your actual input.
Question
I have a fairly static website with just a few basic PHP usage. Now the customer would like to have this website translated. I do have a solution, but it's cumbersome and I was wondering how others are doing it and what is the standard (in frameworks, etc.).
My Way
My way (I have simplified it a bit for the sake of easier understanding): I generate a PHP array for each language from the database and store this array in a language file, like es.php for Spanish.
I then translate a string in HTML using a tr function like this:
Before:<h1>Hello World</h1>
After: <h1><?php echo tr('Hello World'); ?></h1> which gives <h1>Hola Mundo</h1> for Spanish.
The Problem
This is cumbersome and error prone. I have to go through each .php file and replace all the hardcoded strings with this PHP tag with echo.
Is there a better way? How are others doing it? If needed, I can elaborate on my implementation.
You should look into the PHP GETTEXT extension, it is very fast and will scan your PHP files for strings to translate with .MO and .PO files
You then can simply do something like __('Hello World'); or if you already have all the strings with tr('Hello World'); then you could just modify the tr function to pass it through __(string) or gettext(string) like..
function tr($string){
__($string)
}
A little late for you, I suppose but in case someone like me stumbles across this thread... Because I currently have the same problem you do.
Unfortunately, there doesn't appear to be a "non-cumbersome way" to do this with PHP. Everything seems to involve lots of function-calls (if you have a lot of text).
Well... there is ONE convenient way. Not exactly safe though. Manipulating the output buffer before it's sent to the user:
=> http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide
So you could depending on the language chosen just define an array filled with "from->to"-data and replace all the readable text in your buffer by looping through that.
But of course... if you e.g. replace "send" (English) with "senden" (German) and you link to a "send.html", it would break that link.
So if one has to translate not only long, definitely unique strings but also shorter ones, one would have to manipulate only the text that is readable to the user. There is a solution for that too - however, that is JavaScript based:
=> http://www.isogenicengine.com/documentation/jquery-multi-language-site-plugin/
You could always punt and translate your site using Google's Tools and Resources.
Generally, I consider a multilingual site no longer to be "static". I use Drupal to implement sites. It has some excellent internationalization options.
Try this solution. It works for me. It has french and english translation.
Index.php
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>How to Translate your Site in Runtime using Jquery - demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="example">
<h3>How to Translate your Site in Runtime using Jquery - demo</h3>
<div id="content">
<div class="lang_switcher">
<button id="en" class="lang">EN</button>
<button id="fr" class="lang">FR</button>
</div>
<div style="clear:both;"></div>
<!-- nav menu start -->
<ul id="nav">
<li>Home</li>
<li>Peoples >>
<ul>
<li>All list</li>
<li>Online</li>
</ul>
</li>
<li>Articles >>
<ul>
<li>JavaScript</li>
<li>PHP</li>
<li>HTML</li>
<li>CSS</li>
</ul>
</li>
<li>Contact us</li>
</ul>
<!-- nav menu end -->
<div style="clear:both;"></div>
<h2 key="welcome" class="tr">Welcome guests</h2>
<hr />
<div key="a_man" class="tr">A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.</div>
</div>
</div>
</body>
</html>
main.js
// preparing language file
var aLangKeys=new Array();
aLangKeys['en']=new Array();
aLangKeys['fr']=new Array();
aLangKeys['en']['home']='Home';
aLangKeys['en']['peoples']='Peoples >>';
aLangKeys['en']['all_list']='All list';
aLangKeys['en']['online']='Online';
aLangKeys['en']['articles']='Articles >>';
aLangKeys['en']['js']='JavaScript';
aLangKeys['en']['php']='PHP';
aLangKeys['en']['html']='HTML';
aLangKeys['en']['css']='CSS';
aLangKeys['en']['contact_us']='Contact us';
aLangKeys['en']['welcome']='Welcome guests';
aLangKeys['en']['a_man']='A man bribes a rabbit with wicked dentures to run away with him in a sailboat via an ambulance. Bribing Koalas to remain illegally in one place. Trees anchor me in place. / Your mom drives the ambulance, but the city is farther than it appears.';
aLangKeys['fr']['home']='Accueil';
aLangKeys['fr']['peoples']='Peuples >>';
aLangKeys['fr']['all_list']='Toutes les listes';
aLangKeys['fr']['online']='En ligne';
aLangKeys['fr']['articles']='Articles >>';
aLangKeys['fr']['js']='JavaScript';
aLangKeys['fr']['php']='Php';
aLangKeys['fr']['html']='Html';
aLangKeys['fr']['css']='Css';
aLangKeys['fr']['contact_us']='Contactez nous';
aLangKeys['fr']['welcome']='Bienvenue aux invites';
aLangKeys['fr']['a_man']="Un homme soudoie un lapin avec des prothèses méchantes pour s'enfuir avec lui dans un voilier via une ambulance. Corruption des Koalas pour qu'ils restent illégalement à un endroit. Les arbres m'ancrent en place. / Votre mère conduit l'ambulance, mais la ville est plus loin qu'il n'y paraît.";
$(document).ready(function() {
// onclick behavior
$('.lang').click( function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i){
$(this).text(aLangKeys[lang][ $(this).attr('key') ]);
});
} );
});
And some css- main.css
body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:500px;height:500px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius:3px;-webkit-border-radius:3px}
.lang_switcher{float:right;overflow:hidden;}
/* nav menu styles */
#nav,#nav ul{list-style:none;font:10px verdana, sans-serif;border:1px solid #000;background:#fff;position:relative;z-index:200;border-color:#eca #b97 #a86 #edb;border-width:1px 2px 2px 1px;margin:0;padding:0 0 5px}
#nav{height:25px;padding:0}
#nav table{border-collapse:collapse}
#nav li{float:left;padding:0 20px 0 10px}
#nav li li{float:none}
#nav li a li{float:left}
#nav li a{display:block;float:left;color:#888;height:25px;padding-right:5px;line-height:25px;text-decoration:none;white-space:nowrap}
#nav li li a{height:20px;line-height:20px;float:none}
#nav li:hover{position:relative;z-index:300;background:#fff}
#nav a:hover{position:relative;z-index:300;text-decoration:underline;color:#b75}
#nav :hover ul{left:0;top:22px}
#nav a:hover ul{left:-10px}
#nav li:hover li:hover > ul{left:-15px;margin-left:100%;top:-1px}
#nav li:hover > ul ul{position:absolute;left:-9999px;top:-9999px;width:auto}
#nav li:hover > a{text-decoration:underline;color:#b75}
#nav a:hover a:hover ul,#nav a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover ul,#nav a:hover a:hover a:hover a:hover a:hover ul{left:100%;top:-1px}
#nav ul,#nav a:hover ul ul,#nav a:hover a:hover ul ul,#nav a:hover a:hover a:hover ul ul,#nav a:hover a:hover a:hover a:hover ul ul{position:absolute;left:-9999px;top:-9999px}
Do way i translate my website is
Under doctype have lang then your selected lang, eg below,
Then create a php function to get this by $_POST['get'],
and have have that function load up the selected language file/db etc,
I made a class to do mine
class WILang
{
function __construct()
{
$this->WIdb = WIdb::getInstance();
}
public static function all($jsonEncode = true) {
// determine lanuage
$language = self::getLanguage();
//echo $language;
$WIdb = WIdb::getInstance();
//$file = WILang::getFile($language);
//echo $file;
//echo $language;
if ( ! self::isValidLanguage($language) )
die('Language file doesn\'t exist!');
else {
$sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
//$result = array();
while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
echo "{";
foreach ($result as $res) {
echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
//return array($res['keyword'] => $res['translation'] ,);
}
echo "}";
}
}
}
public static function get($key ) //, $bindings = array()
{
// determine language
$language = self::getLanguage();
$WIdb = WIdb::getInstance();
$sql = "SELECT * FROM `wi_trans` WHERE `keyword`=:key AND lang=:lang";
$query = $WIdb->prepare($sql);
$query->bindParam(':key', $key, PDO::PARAM_STR);
$query->bindParam(':lang', $language, PDO::PARAM_STR);
$query->execute();
$res = $query->fetch(PDO::FETCH_ASSOC);
if($res > 0)
return $res['translation'];
else
return '';
}
public static function setLanguage($language)
{
// check if language is valid
if ( self::isValidLanguage($language) ) {
//set language cookie to 1 year
setcookie('wi_lang', $language, time() + 60 * 60 * 24 * 365, '/');
// update session
WISession::set('wi_lang', $language);
//refresh the page
header('Location: ' . $_SERVER['PHP_SELF']);
}
}
public static function getLanguage()
{
// check if cookie exist and language value in cookie is valid
if ( isset ( $_COOKIE['wi_lang'] ) && self::isValidLanguage ( $_COOKIE['wi_lang'] ) )
return $_COOKIE['wi_lang']; // return lang from cookie
else
return WISession::get('wi_lang', DEFAULT_LANGUAGE);
}
private static function getTrans($language)
{
$WIdb = WIdb::getInstance();
//$file = WILang::getFile($language);
//echo $file;
//echo $language;
if ( ! self::isValidLanguage($language) )
die('Language file doesn\'t exist!');
else {
//$language = include $file;
//return $language;
$sql = "SELECT * FROM `wi_trans` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
//$result = array();
while ($result = $query->fetchAll(PDO::FETCH_ASSOC)) {
echo "{";
foreach ($result as $res) {
echo '"' .$res['keyword'] .'":"' . $res['translation'] . '",';
//return array($res['keyword'] => $res['translation'] ,);
}
echo "}";
}
}
}
private static function getFile($language)
{
$WIdb = WIdb::getInstance();
$sql = "SELECT * FROM `wi_lang` WHERE `lang` = :file";
$query = $WIdb->prepare($sql);
$query->bindParam(':file', $language, PDO::PARAM_STR);
$query->execute();
$res = $query->fetch(PDO::FETCH_ASSOC);
//echo $res['lang'];
if ($res > 0)
return $res['lang'];
else
return '';
}
private static function isValidLanguage($lang)
{
$file = self::getFile($lang);
//echo $file;
if($file == "")
//if ( ! file_exists( $file ) )
return false;
else
return true;
}
}
I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?
<html>
<?php
function day()
{
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
<style type="text/css">
body
{
background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
: 'images/night_sheep.jpg'); ?>');
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}
</style>
</html>
Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?
Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:
body {
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
body.day {
background-image: url('images/day_sheep.jpg');
}
body.night {
background-image: url('images/night_sheep.jpg');
}
and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:
<body class="<?php echo day() ? 'day' : 'night'; ?>">
You never declare what $hour is.
<html>
<?php
function day()
{
$hour = date('G');
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
... snip ...