Reading html with php file and execute php code inside the file - php

Can somebody tell me to run php inside an html file that is opened inside an php file.
Its like this.
I have an HTML file like this:
<html>
<head>
<title></title>
</head>
<body>
<h1>Some heading</h1>
<? $sometekst_variable ?>
</body>
</html>
What i whant is to open the file inside my php function and to let the function run the php inside the file. The php variable will be set inside the function where the file is read.
Is there a way to do this?

Use an include. In your top file, do something like
include('otherfile.php');

You can do it via require 'that_template_file';
If you want to catch the html output of that file (e.g. run it, but not print it to the output stream), you can (must) use output buffers, like so:
<?php
function render($tpl) {
// this way it would print out everything to the output, without a chance to grab that
require $tpl;
// OR do it like this:
ob_start();
require $tpl;
$parsed_result = ob_get_contents();
// now you can print out the result or do something else with it...
echo $parsed_result;
// or return it
return $parsed_result;
}
render('template.ext.php'); // note, it doesn't have to be .php... it can be anything
Also note that you can nest calls to ob_start, so you can nest the render function.
Like so:
index.php:
<?php render('template.inc.php'); ?>
template.inc.php:
<div><?php render('header.inc.php'); ?></div>
and so on.

Related

How to properly embed HTML code in PHP function

For a Wordpress plugin, I made a function that contains a big HTML portion (following WP docs, I used ob_start and ob_get_clean to insert it):
function myShortcode() {
ob_start();?>
<!-- here a lot of HTML -->
<?php
return ob_get_clean();
}
I would like to put the HTML outside this function and include or require it.
Is this possible? Is there something I should be aware of? Is it preferable file_get_contents? Any other tip is appreciated, thanks in advance
You can move your html to separate file and then include it as simple php file after ob_start()... Yes it will work, just make sure your view.php template partial is Echoing that html, i.e. You may have html outside of php tags e.g.
File view.php
<?php //Template code starts ?>
ALL HTML HERE
<?php // Template code ends ?>
And your current function in current plugin php file will become:
function myShortcode() {
ob_start();
include(PLUGIN_DIR_PATH/templates/view.php);
return ob_get_clean();
}

how to include code snippet from one php file to another one?

i have just learned about include() function in php, which enables to include whole document into another document. i was wondering how to do the same, if i would like to include not a whole document, but only a snippet of code, from one document into another one.
You can do it with 2 approach:
You can go with #blckbird idea and put your code in a new file and just include it.
You can create a file containing a method foo(), with your snip code. include the file and just call that foo().
Exmple:
// helper.php - contain your snip/reusable code
<?php
function startPage($title){
print '
<!DOCTYPE html>
<html>
<head>
<title>'.$title.'</title>
</head>
<body>';
}
function endPage(){
print '
</body>
</html>';'
}
?>
Now your main file include helper.php and call the method you want.
// main.php
<?php
include("helper.php");
startPage("My Title");
// do your stuff/coding here
endPage();
?>
hope it helps a bit.

Can I load a file in PHP as a string with inline variables?

I've got a simple (but not tiny) template for some HTML, complete with inline variables. I'd like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?
Eg:
$thing="complete sentence";
$test=<<<END
This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.
What I want is something like this:
// "test.html"
<html>
<body>
<p>This will get parsed as a $thing.</p>
</body>
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.html");
echo $test; // This will get parsed as a complete sentence.
How do I achieve this, preferably without a templating library?
<?php
$thing="complete sentence";
$test=file_get_contents("test.php");
echo preg_replace_callback('#\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)#','changeVariables',$test);
function changeVariables($matches)
{
return $GLOBALS[$matches[1]];
}
This code uses preg_replace_callback to check what is variable. But, because we are in function, we cannot directly access script variables. We have to use $_GLOBALS variable which contains every script variable. $matches[1] contains name of matched variable.
Something like this should work...
// "test.php"
This will get parsed as a %s.
// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.php");
printf($test, $thing);
You can use include to simply load the file as if it were part of the calling code.
include("included_file.php");
If you cannot include for some reason, you can read the file contents and eval it.
$content = file_get_contents("included_file.php");
eval($content);
UPDATE:
As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include can work. Your test.html should have this content:
<html>
<body>
<p>This will get parsed as a <?= $thing ?>.</p>
</body>
And eval would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.

Can PHP write html command to another file?

I have one question to ask you.
I have 2 PHP files first one is index.php and another one is body.php
index.php contain HTML template like
<html>
<head>
<title></title>
</head>
<body>
<? include('body.php') ?>
</body>
</html>
and body.php query data from database(such as name, nickname, age).
I need body.php to change tag or add more tag in index.php
How should i do in PHP command?
thanks
In your example, body.php can have any HTML output you need. The output of body.php will be included in your final output.
If you need to make the final output of index.php dependent on the body.php file, (for example to insert a title) you can load your content into variables, which can be outputted later.
<?
include ('body.php');
/* $title and $bodyHTML are set in the include file */
?>
<html>
<head>
<title><? echo $title; ?></title>
</head>
<body>
<? echo $bodyHTML;?>
</body>
</html>
You can use fopen() and fwrite() to modify the content of index.php from body.php (assuming that you have the write permissions, of course).
If you mean change the content while the user is viewing index.php and then change index.php, then that isn't possible without telling the user to "click here and view the new code!" (since at that point, you can no longer use headers to refresh the page).
PHP is not a dynamic content language like, for example, JavaScript.
You can't alter variables in part of the page that has already been output. You can use output buffering to capture the output to that point and then do string substitutions on it
<?php ob_start(); // start buffering output
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
include('body.php');
// Get the contents of the buffer and then clear the buffer
$buffer = ob_get_clean();
// Replace your keyword with a variable loaded from body.php
$buffer = str_replace('%nickname%', $nickname, $buffer);
// output the altered head
echo $buffer;
// Stop buffering and output what we just echoed
ob_end_flush();
?>
</body>
</html>
There are a number of PHP template and theming engines out there that make
doing this kind of thing easier. Smarty is a fairly
popular one. Another one I like is Savant but I'm personally partial to the one I created called Enrober.
write db related stuff in body.php file and call those functions from index.php.
Loop those results and built through related tags and display.
Thats it.........
You could output the entire thing from a php object called domdocument, which allows dynamic creation of html documents.
That way, you could change the tags and their content as dynamically as you want.

HTML into PHP Variable (HTML outside PHP code)

I am new to php and wondering if I can have something like this:
<?php
...
magicFunctionStart();
?>
<html>
<head>...</head>
<body>...</body>
</html>
<?php
$variable = magicFunctionEnd();
...
?>
What I have to use right now is
<?php
...
$variable = "<html><head>...</head><body>...</body></html>"
?>
Which is annoying and not readable.
Have you tried "output buffering"?
<?php
...
ob_start();
?>
<html>
<head>...</head>
<body>...<?php echo $another_variable ?></body>
</html>
<?php
$variable = ob_get_clean();
...
?>
I think you want heredoc syntax.
For example:
$var = <<<HTML
<html>
<head>
random crap here
</html>
HTML;
I'm not really sure about what you are trying to accomplish, but I think something like the heredoc syntax might be useful for you:
<?
$variable = <<< MYSTRING
<html>
<head>...</head>
<body>...</body>
</html>
MYSTRING;
However if you are trying to make HTML templates I would highly recommend you to get a real templating engine, like Smarty, Dwoo or Savant.
Ok what you want to do is possible in a fashion.
You cannot simply assign a block of HTML to a php variable or do so with a function. However there is a number of ways to get the result you wish.
Investigate the use of a templating engine (I suggest you do this as it is worth while anyway). I use smarty, but there are many others
The second is to use an output buffer.
One of the problems you have is that any HTML you have in your page is immediately sent to the client which means it cant be used as a variable in php. However if you use the functions
ob_start and ob_end_fush you can achive what you want.
eg
<?php
somesetupcode();
ob_start(); ?>
<html>
<body>
html text
</body>
</html>
<?php
//This will assign everything that has been output since call to ob_start to your variable.
$myHTML = ob_get_contents() ;
ob_end_flush();
?>
Hope this helps you can read up on output buffers in php docs.
I always recommend to AVOID buffer functions (like ob_start ,or etc) whenever you have an alternative (because sometimes they might conflict with parts in same system).
I use:
function Show_My_Html()
{ ?>
<html>
<head></head>
<body>
...
</body>
</html>
<?php
}
...
//then you can output anywhere
Show_My_Html();
$html_content = '
<p class="yourcssclass">Your HTML Code inside apostraphes</p>
';
echo $html_content;
Its REALLY CRAZY but be aware that if you do it :
<?php echo ""; ?>
You will get it:
<html><head></head><body></body></html>
Keep calm, its only php trying turn you crazy.

Categories