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.
Related
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>
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;
I'm building a CMS and I'm stuck on this problem. I need to write a simple php file for every page and I need to pass an ID and the include function.
Here is my code to write the file:
$filename=mysqli_fetch_array($query))['pagename'];
$fw=fopen("../".$filename,'w',true);
fwrite( "<php
\$id = $id;
include('admin/renderpage.php');
?>");
fclose($fw);
and this is the result, which looks like what I need, only that the variable $id is not an actual variable and include function doesn't work either.
<php
$id = 2;
include('admin/renderpage.php');
?>
Try:
$filename=mysqli_fetch_array($query))['pagename'];
$fw=fopen("../".$filename,'w',true);
fwrite( $fw, "<?php
\$id = $id;
include('admin/renderpage.php');
?>");
fclose($fw);
The PHP open tag is: <?php not <php.
PHP tags
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;
});
I have a problem with 3rd-party-system integration in my drupal site.
Sorry for my english, i'm from russia, but i will try to explain my problem well.
Integration idea:
2 .php files
2 php-script lines (include
function's)
The problem is:
this scripts call to outside perl
(.pl) script. Perl script read the
parameters (parameters transfers by
url) and generate content.
I can't see this perl script, but i
know - hes working, but not in my
page :)
2 php files:
spectrum_view.php
<?php
$url = "http://young.spectrum.ru/cgi-bin/programs_view.pl";
$param = $_GET;
if (!empty($param))
{
$url .= "?";
foreach ($param as $keys=>$value)
{
$url .= "&".$keys."=".urlencode($value);
}
} echo $content = file_get_contents($url);
?>
spectrum_form.php
<?php
$url ="http://young.spectrum.ru/cgi-bin/programs_form.pl";
$params = $_GET;
if (!empty($params))
{
$url .= "?";
foreach ($params as $keys=>$value)
{
$url .= "&".$keys."=".urlencode($value);
}
} echo iconv("windows-1251","utf-8",(file_get_contents($url)));
?>
and the 2 php-lines, wich i insert in my drupal pages
(the first i insert in page http://new.velo-travel.ru/view
and the second in the right block)
include("http://new.velo-travel.ru/themes/themex/spectrum_view.php?$QUERY_STRING");
include("http://new.velo-travel.ru/themes/themex/spectrum_form.php?act=/view$QUERY_STRING");
So, i solved this problem, but not in drupal - only on my Localohost, i just create a 2 page:
form.php:
<?php
$url ="http://young.spectrum.ru/cgi-bin/programs_form.pl";
$params = $_GET;
if (!empty($params)){
$url .= "?";
foreach ($params as $keys=>$value) $url .= "&".$keys."=".urlencode($value);
}
$content = file_get_contents($url);
print $content;
**require_once 'view.php';**
?>
view.php:
<?php
$url = "http://young.spectrum.ru/cgi-bin/programs_view.pl";
$param = $_GET;
if (!empty($param))
{
$url .= "?";
foreach ($param as $keys=>$value)
{
$url .= "&".$keys."=".urlencode($value);
}
}
$content = file_get_contents($url);
print $content;
?>
=(
I'm not entirely sure, as to what you are trying to do. But it seems like you want to generate this content from the perl script. If this is a special page with it's own template, you should move all this code into template.php. This file is made to hold some logic you want to create the content for your page.
Personally I would prefer to make a module to handle all this, but it's probably easier to do this in the theme, with what you got now. It seems like you are making a form, and some content based on the form. This could be done in a module. You could create a Drupal form, and then handle the validation with drupal, and jst submit the data to perl. But if you would want to get it from perl, going with the theme is probably best. So how do you do it?
Implement a preprocess function for the tpl.php file you use.
Create all the logic here, you could copy the php files you use over or just include them. Import, assign the result to a variable the will be accessible in the template file.
Print the variable in your template.
In code this would look something like this:
//template.php file
function mytheme_preprocess_somename(&$vars) {
include('php');
// Do some logic.
$vars['form'] = $result_a;
$vars['my_content'] = $result_b;
}
// your .tpl.php
// Some markup here
<div><?php print $my_content; ?></div>
<div><?php print $form; ?></div>
Now, I'm not sure exactly what you are after, but something like this should help you along. Note it's important what you call your variables inside the template file, as you can overwrite some Drupal variables like $content, which can cause some bugs.
You probably are running into a security issue. Please note allow_url_fopen and allow_url_include - these settings must have accordant settings in your php.ini. Otherwise you can't e.g. include a remote file for security reasons.