How can I include a general html text with php? - php

I want a simple method to include some html text with php functions. Like creating a simple array with functions like: Ex. "about_us_text => About us text example etc.." . Which will be the easiest way to do this ? And how will I include the two files to work as one? Thanks.
$lang = array_merge($lang, array(
'ADD_ATTACHMENT' => 'Upload attachment',
'ADD_ATTACHMENT_EXPLAIN' => 'If you wish to attach one or more files enter the details below.',
'ADD_FILE' => 'Add the file',
'ADD_POLL' => 'Poll creation',

This code will automatically replace {ADD_ATTACHMENT} with Upload attachment
<?php
include 'lang.php';
ob_start();
include ('page_to_display.php');
$html=ob_get_clean();
for ($lang as $k=>$v)
$html=str_replace('{'.$k.'}',$v,$html);
echo $html();
?>

If you have a lengthy html text it is better to put it in its own file and define that file as a translations/constants file. Include that php file in your function/array. keeps it clean
http://php.net/manual/en/language.constants.php
Your constants file lang_constants_en.php might by like
<?php
define('ABOUT_US', '<p>About Us</p>');`
in your function called dump_html()
<?php
include('lang_constants_en.php');
function dump_html(){
echo "Other header html" . ABOUT_US;
}
dump_html();

I just want to use like phpbb3 !
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'ACTION' => 'Action',
'ACTION_NOTE' => 'Action/Note',
And they use {ACTION} for text. That is what I want... not html dump and other things....

Related

PHP: Inserting variables into template file - include() or file_get_contents()?

I'm working on a project where I'm keeping all HTML content separate from the rest of the PHP code. Each instance where any HTML needs to be parsed for PHP variables is sent through a function call. Most these deal with dynamic data from the database.
A simple example of a template file:
<div id='{$data['id']}'>{$data['text']}</div>
The variables in the $data array are passed through a function call where the HTML snippet needs to be added to the output buffer:
$output .= $html->load_template('template_id', array('id' => 123, 'text' => 'Testing'));
The html::load_template() function simply locates the correct text file, and is supposed to load the variables and return the string as HTML. This is where I'm having issues:
public static function load($template, $data=array()) {
ob_start();
include ( TEMPLATE . $template .'.tpl' );
ob_flush();
}
I've tried using include() and file_get_contents(), but to no avail - I'm looking for a simple solution where I can use the {$data['var']} syntax, preferably retaining the template HTML as a simple variable, so it can then be added to the output.
I'm trying to avoid using eval().
Can someone give me some guidance?
I've done the same thing in the past, you can modify your below code like this:
public static function load($template, $data=array()) {
ob_start();
include ( TEMPLATE . $template .'.tpl' );
$getData = ob_get_clean();
preg_match_all("|{([^>].*)}|U", $getData, $getDataArr, PREG_SET_ORDER);
if (is_array($getDataArr) && count($getDataArr) > 0) {
foreach ($getDataArr as $php) {
if (strpos($php[1],'$') !== false) {
$getData= str_replace($php[0], (eval('return $'.str_replace('$', '', $php[1]).';')), $getData);
}
}
}
echo $getData;
}

PHP - send result from a function to included file

I want pass result of a function to an included file in that function. let me explain it with an example .
index.php
$siteurl = $_POST['url'];
function validator($siteurl){
global $lang, $siteurl;
......
......
......
return $output;
}
en.php
$lang = array();
$lang['site_url'] = 'Site url is' .$output. '';
$lang['site_url_delete'] = 'delete' .$output. '';
$lang['site_url_edit'] = 'edit ' .$output. '';
well, now i want pass $output from validator function from index.php to fa.php ($lang).
I put this code in fa.php:
$siteurl = $_POST['url'];
$output = validator($siteurl);
It works but it's dirty work because I don't want to call a function (Validator) to each $lang. is there better way to do this?
All files you include in php share the enclosing scope. Think about this like you copy all code from the included file and insert it to the "main" file instead of the include statement.
So, you can write $output = validator($siteurl) in your index.php file, include your lang.php file and directly use the $output variable.
But, however, it is kinda bad practice to use global variables. It may turn your code to a mess after some time. So, be careful and consider to rethink an architecture of your application.
I've been in a wrong way! found the best solution!
solved my problem with function.sprintf
sprintf($lang['site_url'], $output)
$lang['site_url'] = 'Site url is %s';

Get data config return array

i have two php files config.php look like this:
config.php :
<?php
return array(
'name' => 'Demo',
'age' => 21,
'job' => 'Coder'
);
?>
in file index.php, i using file_get_contents for get data of file config.php
index.php:
$config = file_get_contents('config.php');
echo $config['name'];
but this is not working. somebody can help me?
You include code and not its output.
$config = file_get_contents('config.php');
Sends your file to PHP and generates the output and then sends it back to you, which is not what you have to do for code. You have to do
$config = include('config.php'); // or require / require_once / include_once
The function file_get_contents(file) reads the entire file into a string. That means that it will return a string represntation of the content of the file and NOT source code that you can just use in your main script.
Note: If the path to file is an absolute path, file_get_contents() will execute the php first and return the rendered output of the php file.
Since you want the source of 'config.php' to be available in 'index.php', you have to include it.
Just use include() or include_once().
config.php :
<?
$config = array(
'name' => 'Demo',
'age' => 21,
'job' => 'Coder'
);
?>
index.php:
include('config.php');//or include_once('config.php');
//include makes the content of 'config.php' available exactly as if it was written inside of the document iteself.
echo $config['name'];
Hope this helps!

Include PHP file with parameter

newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.
An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}
Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");
In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));
The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included

PHP Templating

I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment:
Firstly I use fetch_template to load the template contents from the database - this works (and I collect all the templates at startup if you're interested).
I use PHP variables in my template code and in the logic - e.g.:
// PHP:
$name = 'Ross';
// Tpl:
<p>Hello, my name is $name.</p>
I then use output_template (below) to parse through the variables in the template and replace them. Previously I was using template tags with a glorified str_replace template class but it was too inefficient.
/**
* Returns a template after evaluating it
* #param string $template Template contents
* #return string Template output
*/
function output_template($template) {
eval('return "' . $template . '";');
}
My problem, if you haven't already guessed, is that the variables are not declared inside the function - therefore the function can't parse them in $template unless I put them in the global scope - which I'm not sure I want to do. That or have an array of variables as a parameter in the function (which sounds even more tedious but possible).
Does anyone have any solutions other than using the code from the function (it is only a one-liner) in my code, rather than using the function?
Thanks,
Ross
P.s. I know about Smarty and the vast range of templating engines out there - I'm not looking to use them so please don't suggest them. Thanks!
Rather than run through your loop you can use include($template_name).
Or, if you want the content of the output from the template, you can do something like this:
$template_name = 'template.php';
// import the contents into this template
ob_start();
include($template_name);
$content = ob_get_clean();
// do something with $content now ...
And remember, in your template, you can use the often overlooked PHP syntax:
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Alternative syntax is available for if, while, for, foreach and switch ... perfect for manipulating the data in your template. See "Alternative syntax for control structures" for more details.
I'd pass an associative array with variables to replace, then extract() them.
Then you could also pass $_GLOBALS to achieve the same result.
function output_template($template, $vars) {
extract($vars);
eval('return "' . $template . '";');
}
Edit: you might also want to consider string subtitution instead of eval, depending on who's allowed to write your templates and on who specifies which template to load. Then there might be a problem with escaping, too...
Also, expanding on davev's comment eval is a bit ugly.
If you can do something like
function inc_scope( $file , $vars )
{
extract($vars);
ob_start();
require($file);
return ob_get_clean();
}
Then you get to use plain-old-php as your templating language, and you don't get any evil-evals, and "extract" + buffering merely limits the visible scope of the php code in the require.
Create file
config.php
index.php
Create folder
inc
template/default/controller/ main files here home.php, login.php, register.php, contact.php, product.php ...
headet.tpl and footer.tpl include home.php file.
main dir /template/default
config.php code here
/* semu design */
// HTTP URL
define('HTTP_SERVER', 'http://localhost/1/');
// HTTPS URL DISABLE
// define('HTTPS_SERVER', 'http://localhost/1/');
// DİZİNLER
define('DIR_INC', 'C:\wamp\www\1/inc/');
define('DIR_TEMLATE', 'C:\wamp\www\1/template/default/');
define('DIR_MODULES', 'C:\wamp\www\1/template/default/module/');
define('DIR_IMAGE', 'C:\wamp\www\1/image/');
define('DIR_CACHE', 'cache'); // [php cache system turkish coder][1]
// DB
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '123');
define('DB_DATABASE', 'default');
define('DB_PREFIX', '');
index.php code here
<?php
// Version
define('VERSION', '1.0');
// Config file
if (file_exists('config.php')) {
require_once('config.php');
}
// Moduller
require_once(DIR_INC . 'startup.php'); // mysql.php db engine, cache.php, functions.php, mail.php ... vs require_once code
// Cache System
//$sCache = new sCache();
/*$options = array(
'time' => 120,
'buffer' => true,
'load' => false,
//'external'=>array('nocache.php','nocache2.php'), // no cache file
);
$sCache = new sCache($options);*/
// page
$page = isset($_GET['page']) ? trim(strtolower($_GET['page'])) : "home";
$allowedPages = array(
'home' => DIR_TEMPLATE.'controller/home.php',
'login' => DIR_TEMPLATE.'controller/login.php',
'register' => DIR_TEMPLATE.'controller/register.php',
'contact' => DIR_TEMPLATE.'controller/contact.php'
);
include( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages["home"] );
?>
index.php?page=home
index.php?page=login ...
Active class code
<ul>
<li <?php if ( $page == 'home' ) echo 'class="active"'; ?> Home </li>
<li <?php if ( $page == 'login' ) echo 'class="active"'; ?> Login </li>
</ul>
And Token system coming :
index.php?page=home&token=Co54wEHHdvUt4QzjEUyMRQOc9N1bJaeS
Regards.

Categories