Using PHP to determine what HTML to write out - php

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")

You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

Related

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

How can I replace braces with <?php ?> in php file?

I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

Jquery send data within function param

I have this issue with my jquery code:
<?php
//I oppen a text document, read the text inside of it and write it inside my html page.
//When someone clicks on a line, I want to take that very same line and send it via select(String) function.
$handle = fopen($_POST['lien'], 'r');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
//It works when I put a simple string within the select param:
//echo "<div onclick='select(\" text \");'>".$buffer."</div><br/>";
}
fclose($handle);
}
?>
The jquery code :
function select(text){
alert(text);
//$("#selected").html();
}
where do you guys think is the problem ?
Thanks :)
Maybe Your $buffer contains some double-quotes, which then interfere with surrounding double-quotes. Look at produced HTML code if this is the case, maybe You'll see something like this:
<div onclick='select("He said: "Freeze!"")'>
... which Javascript can't parse correctly. If this is the case, consider using:
echo "<div onclick='select(".json_encode($buffer).")'>";
Try to change line:
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
to
echo "<div onclick='select(\" ".rtrim($buffer)." \");'>".$buffer."</div><br/>";
or to:
echo "<div onclick='select($(this).text());'>".$buffer."</div><br/>";

How to use token_get_all to find all T_INLINE_HTML?

I recently heard about a function called token_get_all and I want to find out how to get all of the T_INLINE_HTML out of a php file containing PHP code and HTML. For example, a file like this:
<?php
echo "This is my PHP code";
?>
<html>
<p>Hello, this is the HTML code I want from token_get_all!</p>
</html>
I was attempting to use:
$tokens = token_get_all($filecontents);
$html = $tokens(T_INLINE_HTML);
but that didn't work. How might I do this?
The following code will filter out the tokens of a file which and leave you with only inline HTML ones:
$tokens = token_get_all($filecontents);
$tokens = array_filter($tokens, function($token)
{
return $token[0] == T_INLINE_HTML;
});

How do I use PHP to supply info to JavaScript?

I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).

Categories