Translator in PHP issue - php

I am using a translator class i found online. It works phenomenally when I use it to directly echo the message. The problem occurs when I do conditional checks at the beginning of the page and I need to have the translated text in the variable to then send it to other places on the page to be displayed.
My code:
if ($condition_1){
$message = $translate->__('Text 1');
}
elseif ($condition_2){
$message = $translate->__('Text 2');
}
elseif ($condition_3){
$message = $translate->__('Text 3');
}
This code echos the text in the place where this condition is put, not used as the variable $message and then echos when I need it to. Can you help me to figure out how to use the text as a variable.
If I use the text with no translator class. I can easily use it as a variable.
This is the class i use:
class Translator {
private $language = 'sl';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
echo $this->lang[$this->language][$str];
return;
}
echo $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
echo $str;
}
}
else {
return $this->findString($str);
}
}
}
The translated text is in the a *.txt file, looking like this:
text 1=text 1 translated
text 2=text 2 translated
text 3=text 3 translated

The problem was in the "echo" in the class. I changed the "echo" with "return" and it works like a charm!

Related

PHP is replcing The < & > in a php statement with HTML comments

I am currently trying to create a small template engine for a project that I am working on, and I am using a system where I am replacing {$tag} with a preset tag. So say I put {username} in my template file, it will return a string which is the username. Now I want to go beyond just a simple string replacing a string. So using the same code I put
$tpl->replace('getID', '<?php echo "test"; ?>);
And it didn't work, so when I went to inspect element, I saw that it returned <!--? echo "test"; ?-->...
So now I am just trying to figure out why it returned commented code.
Here is my class file:
class template {
private $tags = [];
private $template;
public function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
public function __construct($templateFile) {
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function set($tag, $value) {
$this->tags[$tag] = $value;
}
private function replaceTags() {
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
public function render() {
$this->replaceTags();
print($this->template);
}
}
And My index file is:
require_once 'system/class.template.php';
$tpl = new template('templates/default/main.php');
$tpl->set('username', 'Alexander');
$tpl->set('location', 'Toronto');
$tpl->set('day', 'Today');
$tpl->set('getID', '<?php echo "test"; ?>');
$tpl->render();
And my template file is:
<!DOCTYPE html>
<html>
<head></head>
<body>
{getID}
<div>
<span>User Name: {username}</span>
<span>Location: {location}</span>
<span>Day: {day}</span>
</div>
</body>
</html>
You're redeclaring PHP in a php file when there is no need to. i.e. you're trying to print <?php which is why it's messing up.
So, you can replace this:
$tpl->set('getID', '<?php echo "test"; ?>');
with this
$tpl->set('getID', 'test');
But, you obviously already know that, you're just trying to go further, the way to do this is by using php inside the set. So, as an idea, you could try this:
$tpl->set('getID', testfunction());
(You're calling testfunction here to define the 'getID' here btw)
So, now you want to write a little function to do something fancy, for the sake of this example:
function testfunction(){
$a = 'hello';
$b = 'world';
$c = $a . ' ' . $b;
return $c;
}
The above should then return hello world in place of {getID}
In reference to your comments - if you want to go one step further and start being more advanced with the return results, you can do the following:
function testfunction(){
$content = "";
foreach ($a as $b){
ob_start();
?>
<span><?php echo $b->something; ?></span>
Some link
<div>Some other html</div>
<?php
$content += ob_get_clean();
}
return $content
}

php currency slows page

I have a page whit ads, and i set the page currency in "RON" and i convert to show also in "Euro" but in the loop is very slow.. I tried to include the script form other php but stil the same... I tried many currency changer but all have the same problem.. slow the page down.. and if i put the code directly in to the loop then tells me an error: that the class could not be repeated.
here is the php currency what i used:
<?php
class cursBnrXML
{
var $currency = array();
function cursBnrXML($url)
{
$this->xmlDocument = file_get_contents($url);
$this->parseXMLDocument();
}
function parseXMLDocument()
{
$xml = new SimpleXMLElement($this->xmlDocument);
$this->date=$xml->Header->PublishingDate;
foreach($xml->Body->Cube->Rate as $line)
{
$this->currency[]=array("name"=>$line["currency"], "value"=>$line, "multiplier"=>$line["multiplier"]);
}
}
function getCurs($currency)
{
foreach($this->currency as $line)
{
if($line["name"]==$currency)
{
return $line["value"];
}
}
return "Incorrect currency!";
}
}
//#an example of using the cursBnrXML class
$curs=new cursBnrXML("http://www.bnr.ro/nbrfxrates.xml");
?>
You can modify the cursBnrXML class to cache parsed currency so that you do not have to loop over entire collection again each look up.
<?php
class cursBnrXML
{
private $_currency = array();
# keep the constructor the same
# modify this method
function parseXMLDocument()
{
$xml = new SimpleXMLElement($this->xmlDocument);
$this->date=$xml->Header->PublishingDate;
foreach($xml->Body->Cube->Rate as $line)
{
$this->currency[$line["currency"]]=array(
"value"=>$line,
"multiplier"=>$line["multiplier"]
);
}
}
# modify this method too
function getCurs($currency)
{
if (isset($this->_currency[$currency]))
{
return $this->_currency[$currency]['value'];
}
return "Incorrect currency!";
}
}
//#an example of using the cursBnrXML class
$curs=new cursBnrXML("http://www.bnr.ro/nbrfxrates.xml");
?>

php: if current url contains "/demo" do something

I want to check if my current URL contains "/demo" at the end of the url, for example mysite.com/test/somelink/demo to do something.
Here is my attempt :
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'mysite.com/test/somelink/demo')
{
// Do something
}
else
{
// Do something
}
This seems to work fine, but the problem is that /somelink needs to by dynamic.
Any suggestion on how can I do this ?
Thank you !
Edit:
<?php
/* An abstract class for providing form types */
abstract class ECF_Field_Type {
private static $types = array();
protected $name;
/* Constructor */
public function __construct() {
self::register_type( $this->name, $this );
}
if(basename($_SERVER['REQUEST_URI']) == 'stats'){
echo "Hello World";
}
/* Display form field */
public abstract function form_field( $name, $field );
/* Display the field's content */
public function display_field( $id, $name, $value ) {
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
/* Display field plain text suitable for email display */
public function display_plaintext_field( $name, $value ) {
return "$name: $value";
}
/* Get the description */
abstract public function get_description();
}
?>
Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
<?php
if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
// Do something
} else {
// Do something else
}
?>
This post has PHP code for simple startsWidth() and endsWith() functions in PHP that you could use. Your code would end up looking like:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}
But one thing you might want to do in addition to that is convert $host to lowercase so the case of the URL wouldn't matter. EDIT: That would end up looking like this:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))
you can use strpos
$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo'))
{
// Do something
echo "in Demo";
}
else
{
// Do something
echo "not in Demo";
}
$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }

properly using variable variables for multilanguage feature

I implemented a multilanguage feature for my web application. I get the values by this
echo $lang['the key here'];
and i keep the values in a separate fiels like this
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
so i want if somebody calls a undefined key like $lang['sdefscfef'] , insted of printing white space, I want to print the key name i.e 'sdefscfef'
I want to make it as a function
function translate($string) {
if(! isset($string)) {
echo THE KEY;
}
else {
echo $string;
}
}
translate($lang['asdadad']);
and to print the key
Instead of printing the array directly I would create a function (_() is common) and use it like so:
echo _('Welcome');
And the _() function would then look in the $language array:
function _ ($str) {
global $language;
return isset($language[$str]) ? $language[$str] : $str;
}
Something like that.
If you want to avoid using a global variable you can wrap all of this in a class like this:
class Lang {
private $lang = array();
public static translate ($str) {
return isset(self::$lang[$str]) self::$lang[$str] : $str;
}
}
And then, to avoid having to type Lang::translate() everywhere you can do this:
function _ ($str) {
return Lang::translate($str);
}
Here's an example of a little more advanced Language class: http://code.google.com/p/sleek-php/source/browse/trunk/Core/Lang.php
Use simply:
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
....
function getTranslation($key) {
global $lang;
if (isset($lang[$key])) {
return $lang[$key];
} else {
return $key;
}
}
// Usage:
echo getTranslation('confirm'); // Prints 'Confirm the message'
echo getTranslation('sjdhj'); // Prints 'sjdhj'

PHP class doesn't echo another php page at the appropriate place

Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>

Categories