Language translation using PHP - php

Hi i am devloping sample site in php i need to translate whole website in to persian. how can it possible in php?? I have tried using the following code.. This code will working fine for deutsch conversion.
1. class.translation.php
<?php
class Translator {
private $language = 'en';
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);
}
}
}
?>
2.Register.php
<?php
require_once('class.translation.php');
if(isset($_GET['lang']))
$translate = new Translator($_GET['lang']);
else
$translate = new Translator('en');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><?php $translate->__('CSS Registration Form'); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15"/>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
</head>
<body>
<form action="" class="register">
<h1><?php $translate->__('Registration'); ?><a class="flag_deutsch" title="deutsch" href="register1.php?lang=de"></a><a class="flag_english" title="english" href="register1.php"></a></h1>
<fieldset class="row1">
<legend><?php $translate->__('Account Details'); ?></legend>
<p>
<label><?php $translate->__('Email'); ?> *</label>
<input type="text"/>
<label><?php $translate->__('Repeat email'); ?> *</label>
<input type="text"/>
</p>
</fieldset>
<div><button class="button"><?php $translate->__('Register'); ?> »</button></div>
</form>
</body>
</html>
Is it possible to transilate to other laguages using this code?? I changed register1.php?lang=de to register1.php?lang=fa(persian).. But nothing hapens..anybody plese help

AS per me you can try this method.This method is already implemented in our system and it is working properly.
Make php file of each language and define all the variables and use those variables in pages.
for e.g
For english
english.php
$hello="Hello";
persian.php
$hello=html_entity_decode(htmlentities("سلام"));
Now use this variable to page like this.
your_page.php
<label><?php echo $hello; ?></label>
You have load specific language file as per get language variable from URL.
It is better that you have define this language variable into config file.
config.php
if(isset($_GET['lang']) && $_GET['lang']=='persian')
{
require_once('persian.php');
}
else
{
require_once('english.php');
}

If I were you, I'd do it like this:
/inc/lang/en.lang.php
define('_HELLO', 'Hello');
/inc/lang/fa.lang.php
define('_HELLO', 'سلام');
index.php
// $_SESSION['lang'] could be 'en', 'fa', etc.
require_once '/inc/lang/' . $_SESSION['lang'] . 'lang.php';
echo _HELLO;
Benchmark: Constants vs. Variables
Here you see why I offered using Constants not Variables:
const.php
echo memory_get_usage() . '<br>'; // output: 674,576
for ($i = 0; $i <= 10000; $i++) {
define($i, 'abc');
}
echo memory_get_usage() . '<br>'; // output: 994,784
var.php
echo memory_get_usage() . '<br>'; // output: 674,184
for ($i = 0; $i <= 10000; $i++) {
$$i = 'abc';
}
echo memory_get_usage() . '<br>'; // output: 2,485,176

original from #rbenmass :
try this:
function translate($q, $sl, $tl){
$res= file_get_contents("https://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$sl."&tl=".$tl."&hl=hl&q=".urlencode($q), $_SERVER['DOCUMENT_ROOT']."/transes.html");
$res=json_decode($res);
return $res[0][0][0];
}
//example--
echo translate("اسمي منتصر الصاوي", "ar", "en");

From an Perl trans script I extracted the following for 100% free php google translation this function:
See working demo on http://ogena.net
function translate($q, $sl, $tl){
if($s==$e || $s=='' || $e==''){
return $q;
}
else{
$res="";
$qqq=explode(".", $q);
if(count($qqq)<2){
#unlink($_SERVER['DOCUMENT_ROOT']."/transes.html");
copy("http://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$sl."&tl=".$tl."&hl=hl&q=".urlencode($q), $_SERVER['DOCUMENT_ROOT']."/transes.html");
if(file_exists($_SERVER['DOCUMENT_ROOT']."/transes.html")){
$dara=file_get_contents($_SERVER['DOCUMENT_ROOT']."/transes.html");
$f=explode("\"", $dara);
$res.= $f[1];
}
}
else{
for($i=0;$i<(count($qqq)-1);$i++){
if($qqq[$i]==' ' || $qqq[$i]==''){
}
else{
copy("http://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$s."&tl=".$e."&hl=hl&q=".urlencode($qqq[$i]), $_SERVER['DOCUMENT_ROOT']."/transes.html");
$dara=file_get_contents($_SERVER['DOCUMENT_ROOT']."/transes.html");
#unlink($_SERVER['DOCUMENT_ROOT']."/transes.html");
$f=explode("\"", $dara);
$res.= $f[1].". ";
}
}
}
return $res;
}
}
//sample usage
echo translate("Goede dag dames en heren", "nl", "en");

As i can read from the code, the translator class loads the translation data from en.txt file, if you want have 'fa' translation, just create fa.txt as copy of en.txt with all translations and edit and translate fa.txt to persian...
Hope it helps

#rbenmass
Thank You :-)
I think it have to be , because it runs good for me :
/*
original from #rbenmass :
function translate($q, $sl, $tl){
if($s==$e || $s=='' || $e==''){
return $q;
}
**/
function translate($q, $sl, $tl){
if($sl==$tl || $sl=='' || $tl==''){
return $q;
}
// ... //

Related

PHP functions not giving the expected output

I am new to php so can anyone tell me why when I open the HTML, it is not showing “5! is 120” as it should be and am instead getting:
Applications
", $num, "! is ", factorial ($num), ".
"; } else { echo "
Please enter a positive integer.
"; } echo "
Return to the Entry Page
"; ?>
PHP functions
<?php
function isPositiveInteger ($n) {
$result = false;
if (is_numeric($n))
if ($n == floor($n))
if ($n>0 )
$result = true;
return $result;
}
function factorial ($n) { // declare the factorial function
$result = 1; // declare and initialise the result variable
$factor = $n; // declare and initialise the factor variable
while ($factor > 1) { // loop to multiple all factors until 1
$result = $result * $factor;
$factor--; // next factor
} // Note that the factor 1 is not multiplied
return $result;
}
?>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="product" />
<meta name="keywords" content="HTML5, tags" />
<meta name="author" content="Ib" />
<title>Product</title>
</head>
<body>
<?php
include ("mathfunctions.php");
?>
<h1> Applications </h1>
<?php
$num=5;
if (isPositiveInteger($num)) {
echo "<p>", $num, "! is ", factorial ($num), ".</p>";
} else {
echo "<p> Please enter a positive integer. </p>";
}
echo "<p> <a href='factorial.html'> Return to the Entry Page </a></p>";
?>
</body>
</html>

Call an anonymous function from another

I have an anonymous function that works when called directly. However, when I try to call it from another anonymous function, I get the error
Fatal error: Function name must be a string in ...(fileName)
Here is the complete code. Appreciate any thoughts on why this is failing.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
$ringW = 16; $ringCx = 8;
$ringH = 16; $ringCy = 8; $ringR = 7;
$penWidth = 2;
$svgCircle = function ($fillColor, $ringColor)
use ($ringW, $ringH, $ringR, $ringCx, $ringCy, $penWidth) {
echo "<svg width=\"$ringW\" height=\"$ringH\">";
echo "<circle cx=\"$ringCx\" cy=\"$ringCy\" r=\"$ringR\" " .
"stroke=\"$ringColor\" stroke-width=\"$penWidth\" fill=\"$fillColor\" />\n";
echo "</svg>\n";
};
$pac = function ($condition) {
if ($condition)
// echo "Hello world\n"; // pass
$svgCircle("yellow", "green"); // fails
};
?>
<head>
<title>LVCC Algorithm</title>
</head>
<body>
<?php
$pac(1);
$svgCircle("yellow", "green"); // pass
$svgCircle("yellow", "green");
?>
</body>
</html>
You forgot to make $svgCircle available to your second function
$pac = function ($condition) use ($svgCircle) {...};
^^^^^^^^^^^^^^^^

How can I change a value on my html template from a class?

This is my first attempt with OOP. I want to modify some values from a class, but I can't figure out how to do that from a different file. If I try to do that from where I have the class is working.
So, all I want is basic html page where i can modify some values.
HTML page
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
My class.php
<?php
class show {
public function setTitle ($t) {
$this->title = $t;
}
public function seth1 ($h1) {
$this->h1 = $h1;
}
public function getTitle () {
return $this->title;
}
public function geth1 () {
return $this->h1;
}
public function render () {
$s = "<!DOCTYPE html>
<html>
<body>";
$s .= "<title>";
$s .= $this->title;
$s .= "<title>";
$s .= "<h1>";
$s .= $this->h1;
$s .= "</h1>";
$s .= "<p>and so on</p>
</body>
</html>";
echo $s;
}
}
?>
index.php
<?php
include dirname(__FILE__) . '/inc/class.php'; // the above example
$s = new show;
$s->setTitle('title');
$s->seth1('h1');
$s->render();
?>
This is just an example of what I'm trying to accomplish. All I get is a blank page...
Is it just me, or are you missing your call to $s->render() ?

PHP code is showing when i show the source in the browser

I have tried to use templates to be able to make a multilingual web site, so i created a folder called languages containing en.php and fr.php
here is the code for en.php:
<?php
class Index {
public $filename;
public $assigned_vars = array();
public function set($key, $value) {
$this -> assigned_vars[$key] = $value;
}
public function display() {
if (file_exists($this -> filename)) {
$output = file_get_contents($this -> filename);
foreach ($this->assigned_vars as $key => $value) {
$output = preg_replace('/{' . $key . '}/', $value, $output);
}
echo $output;
} else {
echo "*** Missing template ***";
}
}
}
$index = new Index;
$index -> filename = "templates/index1.php";
$index -> set('page_title', "Welcome");
$index -> set('first_name', "Welcome to our website.");
$index -> display();
?>
and here is the code for fr.php:
<?php
class Index {
public $filename;
public $assigned_vars = array();
public function set($key, $value) {
$this -> assigned_vars[$key] = $value;
}
public function display() {
if (file_exists($this -> filename)) {
$output = file_get_contents($this -> filename);
foreach ($this->assigned_vars as $key => $value) {
$output = preg_replace('/{' . $key . '}/', $value, $output);
}
echo $output;
} else {
echo "*** Disparus modèle ***";
}
}
}
$index = new Index;
$index -> filename = "templates/index1.php";
$index -> set('page_title', "Bienvenue");
$index -> set('first_name', "Bienvenue sur notre site.");
$index -> display();
?>
then i created a folder called templates and created a file called index1.php
and here is index1.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{page_title}</title>
</head>
<body>
{first_name}
<br/>
english
French<br />
<?php
echo strftime("Y", time());
?>
</body>
</html>
and then i created the regular index.php
and here is the code for index.php:
<?php
if (isset($_GET['lang'])) {
setcookie('language_test', $_GET['lang'], time() + (60 * 60 * 24 * 7));
if ($_GET['lang'] == "fr") {
require ('languages/fr.php');
} else {
require ('languages/en.php');
}
} else {
require ('languages/en.php');
}
?>
here is my problem when i try to show index.php in my browser it works fine but the php code in index1.php doesn't show any of this strftime();, but when i try to view the source of this
index.php
it's showing me this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome</title>
</head>
<body>
Welcome to our website.
<br/>
english
French<br />
<?php
echo strftime("Y", time());
?>
</body>
</html>
thanks in advance. and sorry for being so long and sorry for my awful english.
When you are invoking file_get_contents($this -> filename); it just converts strftime("Y", time()); part as string. So it does not execute.
In the index1.php you should use {time} instead of
<?php
echo strftime("Y", time());
?>
So It'll look like
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{page_title}</title>
</head>
<body>
{first_name}
<br/>
english
French<br />
{time}
</body>
Now add time in en.php or fr.php like bellow
$index -> set('time', strftime("%Y", time()));
Its better not to re-invent a template library. There are plenty available. See this blog post top 25 php template engines
Thanks to all those who tried to help me.
i looked at another question and i found my answer without using smarty
<?php
class Index {
public $filename;
public $assigned_vars = array();
public function set($key, $value) {
$this -> assigned_vars[$key] = $value;
}
public function display() {
if (file_exists($this -> filename)) {
ob_start();
include ($this -> filename);
$output = ob_get_clean();
foreach ($this->assigned_vars as $key => $value) {
$output = preg_replace('/{' . $key . '}/', $value, $output);
}
echo $output;
} else {
echo "*** Missing template error ***";
}
}
}
$index = new Index;
$index -> filename = "templates/index1.php";
$index -> set('page_title', "Welcome");
$index -> set('content', "Welcome to our website.");
$index -> display();
?>
the problem as Shiplu stated that i invoked file_get_contents();
and now i can do my for loop without any problems in index1.php
so i hope i got something useful for you guys
and really this is the best website ever,
Thanks to everyone tried to help me.
Have a wonderful day all of you

Access a PHP array from JavaScript

I have the following code where I declare a PHP array variable and inside a function, I put some data into the array. I also display buttons mapped to each index of the array that will show the data in the PHP array for that index number.
When testing on a browser, I don't get the right answer. I checked the page source, it had code like data_array = ["<?php echo implode ('',Array); ?>"]; instead of the text from the Array.
What am I doing wrong and what should I do to get the correct output? (BTW, I tried to execute the same without declaring the function and it seemed to work, but I need a function for my work and can't take that approach).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<html lang="en">
<head>
<title>Example</title>
<?php
$giant_says = array();
function display() {
global $giant_says;
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
echo "<div id='content'>";
echo $giant_says[0];
echo "</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\"";
$i += 1;
}
}
?>
<script type="text/javascript">
function addtext(index) {
giantSays = ["<?php echo implode ('","', $giant_says); ?>"];
document.getElementById('content').innerHTML = giantSays[index];
}
</script>
</head>
<body>
<?php
display();
?>
</body>
</html>
You have the order wrong, which is causing the implode() to compress an empty array. I also suggest using json_encode() instead of implode(). It exists for this type of thing - updated example below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<html lang="en">
<head>
<title>Example</title>
<?php
$giant_says = array();
function display(&$giant_says) {
// Calculate the array (referenced)
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
// Return the HTML, to display later
ob_start();
echo "<div id='content'>";
echo $giant_says[0];
echo "</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\">";
$i += 1;
}
$Return = ob_get_contents();
ob_end_clean();
return $Return;
}
$Display = display($giant_says);
?>
<script type="text/javascript">
function addtext(index) {
giantSays = <?php echo json_encode($giant_says); ?>;
document.getElementById('content').innerHTML = giantSays[index];
}
</script>
</head>
<body>
<?php
echo $Display;
?>
</body>
</html>
You're trying to implode the $giant_says array before you've filled it (you're calling display() after the implode when the call needs to happen before).
The problem is that you call the display method, that fills the content after the html part with the javascript is sended.
the html code is "like" making an "echo 'html'" from your php. Your html is already processed but the display method is not called. call the method before the html code.
Example:
<?php
$giant_says = array();
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
function display() {
global $giant_says;
echo '<div id="content">'.$giant_says[0]."</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");\" />";
$i += 1;
}
}
?>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function addtext(index) {
giantSays = ["<?php echo implode ('","', $giant_says); ?>"];
document.getElementById('content').innerHTML = giantSays[index];
return false;
}
</script>
</head>
<body>
<?php display(); ?>
</body>
</html>

Categories