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>
Related
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) {...};
^^^^^^^^^^^^^^^^
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() ?
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;
}
// ... //
Ok, I am using a PHP editing form (previous person built) that submits data into an MSSQL database this works fine however when the information is submitted into the database and later retrieved the the form page (for editing) there is a <br> at the beginning of the text. If the fields start with a <ul> that <br> is not inserted. I have been trying to figure out how to stop this. One thing I tried ends up removing all <br> in the text which makes the formatting disappear, How can I keep it from inserting the <br> at the top but keeping the <br> everywhere else? here is the code I have: ( I am giving you everything up to the first field where I have the issue appear)
function fromhtml ($x) {
$x = preg_replace("/<p>/i","\n\n",$x);
//$x = preg_replace("/<br>/i","\n",$x);
$x = preg_replace("/<li>/i","\n<li>",$x);
return $x;
}
$PHP_SELF = $_SERVER['PHP_SELF'];
$course_id = #$_GET["course"];
if ($course_id == "") {
$sqlquery = "SELECT id, title, goals, outline, reference, deliverymode, updated2 = CONVERT(VARCHAR(19), updated, 120)
FROM courses WHERE division_id = '$division_id' ORDER by id";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
print "<table border=1 id=\"content_table\"><tr><th>ID</th><th>Title</th><th>Status</th><th>Last modified</th></tr>\n";
$i = 0;
while ($number > $i) {
$course_id = mssql_result($result,$i,"id");
$reference = mssql_result($result,$i,"reference");
$updated = mssql_result($result,$i,"updated2");
print "<tr><td>";
if ($reference == "") {
print "<a href=$PHP_SELF?division=$division_id&course=$course_id>$course_id</a>";
} else {
print "$course_id";
}
print "</td><td>";
print mssql_result($result,$i,"title");
print "</td><td>";
if ($reference == "") {
if ( (mssql_result($result,$i,"goals")=="") and (mssql_result($result,$i,"outline")=="") ) {
print "<b>No syllabus, or incomplete</b></td>";
}
} else {
print "Based on $reference";
}
print "</td><td>$updated</td>\n";
print "</tr>\n";
$i++;
}
print "</table>";
exit;
}
$sqlquery = "SELECT * FROM courses WHERE id = '$course_id'";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
if ($number == 0) {
print "<html><body>";
print "No course with the ID \"$course_id\" exists in the course database.";
print "</body></html>";
exit;
}
$i = 0;
$description = fromhtml(mssql_result($result,$i,"description"));
print "<html><head><title>DACC Course Syllabus - $course_id</title>";
print "<script language=\"JavaScript\" type=\"text/javascript\" src=\"/rte/richtext2.js\"></script>";
?>
<script language="JavaScript" type="text/javascript">
<!--
initRTE("/rte/images/", "/rte/", "");
//-->
function submitForm() {
updateRTEs();
document.edit-course.submit();
return false;
}
</script>
<?php
print "</head><body>\n";
//Begin Form
print "<form name=\"edit-course\" id=\"edit-form\" method=\"post\" action=\"write.php?course=$course_id\" onSubmit=\"return submitForm()\">\n";
print "<fieldset>";
print "<label for=\"description\">Course Description</label>";
$description=addslashes(preg_replace('`[\r\n]`','',$description));
?>
<script language="JavaScript" type="text/javascript">
<!--
writeRichText('description', '<?php print $description; ?>', 200, 300, true, false);
//-->
</script>
<?php
print "</fieldset>";
It that BR is at very very beginning of string then use this
$x = preg_replace("/^<br(\/|)>/i","\n",$x);
instead of that commented line
preg_replace has a fourth parameter, $limit. Setting this to 1 would limit the preg_replace to the first occurence. Alternatively you could use the regular expression ^<br>. This would only replace <br> when it is at the beginning of the string.
Edit: Sorry, I misunderstood your problem. Use $variable=preg_replace("/^<br>/i", "", $variable); to strip the first <br>.
So, I have a postgresql database and I'm querying a particular column's values and assigning each value to a javascript array. Now I have a javascript function which outputs this data on a map. When i test the array manually (Entering the respective array index one by one), it returns the output perfectly alright. But in a loop (When i want to output all at once), i can only see the first element's output. The rest of the array is simply ignored or there's an error. I don't understand where the mistake is. Here's the code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyC0HZ81Ea8Jy8fJ6zm6_uvPp8UhLg5mczo&sensor=true"></script>
<script type="text/javascript" src="GeoJSON.js"></script>
<script type="text/javascript" src="polygon.js"></script>
<script type="text/javascript">
var geojson_Polygon = new Array();
function kaushik()
{
<?php
require("header.php");
$connection = pg_connect($full);
if(!$connection)
{
pg_close($connection);
}
$result = pg_query($connection, "SELECT ogc_fid, ST_AsGeoJSON(wkb_geometry), name FROM features");
if (!$result)
{
exit;
}
$i = 0;
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[1];";
echo "\n";
echo "\n";
$i++;
}
?>
for (var j=0; j<317; j++)
{
showFeature(geojson_Polygon[j]);
}
}
</script>
If what you want to do is build a JS array , then just do:
<script type="text/javascript">
var data = [ <?php
// --- snip
$first = true;
while ($row = pg_fetch_row($result))
{
if ( $first )
{
$first = false;
}else{
echo ',';
}
echo $row[$i]
}
// ---- snip
?> ];
</script>
i think you should do
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[$i];";
echo "\n";
echo "\n";
$i++;
}
otherwise the value is always the same
Just read the rows into a php array and then assign it as json.
<script>
...
var geojson_Polygon = <?php echo json_encode($all_rows); ?>;
....