PHP create a nicer way to echo variables - php

I am looking for a way to replace <?php echo $something; ?> with another notation like {$something}. But: No smarty or sth similar is used!
More detailed:
At the moment, I got a .php file (with some variables inside), which includes the file "template.php". In this template file, I don't want having to use the (not very user-friendly) php notation, but replace certain strings inside this file like mentioned above. Is there any way to do so? It would be probably the best, if you could replace strings like <title></title> with <title><?php echo $title; ?></title>.
Maybe (my thoughts) I should just write the whole code into a php variable, then do some preg_replace and echo it? Or is there a more beautiful solution?

Did a similar thing several years ago wherein I had to replace several variables in an email template. What I ended up implementing was doing a str_replace on several tags. Like you, I don't want to have PHP notations or to escape characters in the template file as much as possible
Example:
template.php
<html>
<head>
<title>[EMAIL_TITLE]</title>
</head>
<body>
Hello [USER_NAME],
Login here [LOGIN_LINK].
</body>
</html>
processor.php
$body = file_get_contents( 'template.php' );
str_replace( '[EMAIL_TITLE]', $emailTitle, $body );
str_replace( '[USER_NAME]', $userName, $body );
str_replace( '[LOGIN_LINK]', $userName, $body );
I've sinced changed implementation though to make use of PHP short tags. Using the same previous example, you could try:
template.php
<html>
<head>
<title><?= $params['title']; ?></title>
</head>
<body>
Hello <?= $params['userName']; ?>!
</body>
</html>
processor.php
$params = array(
'title' => $siteTitle,
'userName' => $userName
);
ob_start();
require_once( 'template.php' );
$body = ob_end_clean();

There are a few notations you can try. One that I prefer for templates is simply:
<?php
echo <<<HTML
<html>
<head>
<title>$title</title>
</head>
<body>
$body
</body>
</html>
HTML;
?>
And then in your content file, you do something like:
<?php
$title = 'My Page!';
$body = '<p>My Content!</p>';
include './template.php';
?>
With this, you don't have to escape singe and double quotes, and it's easy to make changes later.
You can also read in the file to a string and use preg_replace like you said. The easiest way would be with an array to manually go through the file and pull out the place holders. But this is a slow solution if you have high traffic and a lot of variables.

Related

Using PHP as Template Engine and having a thin Template

I'm using PHP as a template engine per this suggestion: https://stackoverflow.com/a/17870094/2081511
I have:
$title = 'My Title';
ob_start();
include('page/to/template.php');
$page = ob_get_clean();
And on page/to/template.php I have:
<?php
echo <<<EOF
<!doctype html>
<html>
<title>{$title}</title>
...
EOF;
?>
I'm trying to remove some of the required syntax from the template pages to make it easier for others to develop their own templates. What I would like to do is retain the variable naming convention of {$variable} but remove these lines from the template file:
<?php
echo <<<EOF
EOF;
?>
I was thinking about putting them on either side of the include statement, but then it would just show me that statement as text instead of including it.
Well, if you want a VERY simple templating solution, this might help
<?php
$title = 'My Title';
// Instead of including, we fetch the contents of the template file.
$contents = file_get_contents('template.php');
// Clone it, as we'll work on it.
$compiled = $contents;
// We want to pluck out all the variable names and discard the braces
preg_match_all('/{\$(\w+)}/', $contents, $matches);
// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value.
foreach ($matches[0] as $index => $tag) {
if (isset(${$matches[1][$index]})) {
$compiled = str_replace($tag, ${$matches[1][$index]}, $compiled);
}
}
echo $compiled;
Template file would look like this
<html> <body> {$title} </body> </html>

Weird HEREDOC output order

I am using (or at least tying to) PHP HEREDOC function as a templating engine. I have implemented external caller string that can directly process external functions in HEREDOC, and that works successfully.
The problem I am facing now is that the order of certain functions appear to take precedence and execute first, regardless of other functions and/or code inside the specific HEREDOC.
How to fix that?
(Please note I am a PHP beginner. I have done my homework, but couldn't find a solution. Thanks.)
FUNCTION PROCESOR:
function heredoc($input)
{
return $input;
}
$heredoc = "heredoc";
HEREDOC TEMPLATE:
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
The issue at hand is with "{$heredoc(display_all_articles_in_a_html_table())}" call, which outputs before everything else, resulting in a broken HTML.
Any help appreciated, I am banging my head with this for quite a while now.
UPDATE:
using stuff posted in comments i tried to do something else, but this is ugly as hell, and I would have issues editing this at later date.
function testout()
{
$title = "This is document title";
echo "<!DOCTYPE html>";
echo '<html lang="en">';
echo "<head>";
echo '<meta charset="utf-8">';
echo "<title>". $title . "</title>";
echo "</head>";
echo "<body>";
echo splicemaster_return_message();
echo splice_quick_add_article_form();
echo display_all_articles_in_a_html_table();
echo "</body>";
echo "</html>";
}
(How it looks like is not important - I have a HTML processor function.)
UPDATE 2
OK, so I found "dirty" fix, tho that doesn't explain why the engine works as it does. (I also tested on another machine, with diff. php):
function splicemaster_return_full_page()
{
global $heredoc;
$title ="This is document title";
echo <<<HEREDOC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{$heredoc(splice_html_title($title))}
</head>
<body>
{$heredoc(splicemaster_return_message())}
{$heredoc(splice_quick_add_article_form())}
HEREDOC;
echo <<<HEREDOC
{$heredoc(display_all_articles_in_a_html_table())}
</body>
</html>
HEREDOC;
}
You shouldn't be using heredoc here. Or really be trying to render an entire html document within a function. This is how html should be rendered with php.
Note: I'm also pretty sure you can't call functions in a heredoc statement.
<?php $title = "This is document title"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo splice_html_title($title); ?>
</head>
<body>
<?php
echo splicemaster_return_message()
. splice_quick_add_article_form()
. display_all_articles_in_a_html_table();
?>
</body>
</html>
You can see how much cleaner this is, which makes it much easier to edit, when needed. You just put this in a file 'page.php' for example.
include_once('page.php');
And include it where ever you would call that function splicemaster_return_full_page.
I asked this (similar) question on other site while seeking why this happens, and found the culprit.
The problem was in called functions that echo (or print) output, instead returning it. When I switched to return, the code outputs appropriately.

How to change TITLE dynamically after the header is included [duplicate]

This question already has answers here:
How to dynamically change a web page's title?
(20 answers)
Closed 8 years ago.
I would like to change the title of the HTML page based on the content, but im including only the content below the header part, so i have to change the title from this included php. To explain:
<html>
<header><title>I would like to change</title></header>
<!--CONTENT-->
<?
include "pages/some_page.php";
?>
</html>
How could i do that? Anyone can help in this?
You cant do that without a nasty hack.
What you should do is perform all your logic BEFORE you output html. A simple example follows:
<?php
//index.php
//perform logic and set variables before any html
$page = isset($_GET['menu'])?$_GET['menu']:'home';
switch($page){
case 'home':
$title = ' welcome to myco.ltd';
$content = 'pages/home.php';
break;
case 'about':
$title = 'about us';
$content = 'pages/about.php';
break;
case 'contact':
$title = 'get in touch';
$content = 'pages/contact.php';
break;
}
//the following html could be in a separate file and included, eg layout.php
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<!--menu and other shared html here-->
<?php include $content;?>
<!-- shared footer stuff here-->
</body>
</html>
This is essentially a VERY barebones router script, an essential component of any framework. I would highly recommend you consider a lightweight framework rather than write everything from scratch. http://fatfreeframework.com/home would be a great start
The function below will let you change document title, meta keywords and meta description. You may use it anywhere in your application.
Just be sure to turn on output buffering using ob_start() before the function is called. I prefer including it at the top of application, just after all global settings are loaded.
function change_meta_tags($title, $keywords, $description){
$output = ob_get_contents();
if (ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/", "/<meta name=\"keywords\" content=\"(.*?)\" \/>/", "/<meta name=\"description\" content=\"(.*?)\" \/>/");
$replacements = array("<title>$title</title>", "<meta name=\"keywords\" content=\"$keywords\" />", "<meta name=\"description\" content=\"$description\" />");
$output = preg_replace($patterns, $replacements, $output);
echo $output;
}
Use javascript in some_page.php .
<?php echo "<script>document.title = '".$dynamicTitleVariable."';</script>"; ?>
Pending what you are trying to base the content off of, this could easily be done via an MVC-style setup. In your controller, you would generate the title based off of content that could be grabbed and pass this through to the view as a variable. Then, in your view have the title be dynamically set:
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
</html>
This should also work fine with SEO capability, as crawlers will be able to interpret this far better than they would JavaScript.

What method should I use for later set a variable and then echo the page title

I'm trying to avoid to query my database twice: for set <title> attribute and also for echo the page title. I want to query it just one time:
Example:
<html>
<head>
<?php
// how should I use here ob_start() ? Is there any other possible way to achieve this?
$title = "";
echo '<title>', $title, '</title>'; // this should be in the end <title>value of $row['page_title']</title>
?>
</head>
<body>
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title']; // I want that this assignment to set the variable in the top
// I know that for this job I can use ob_start() but I didn't used it until now
// and I will really appreciate any help from you.
?>
<h1><?php echo $title; ?></h1>
</body>
</html>
I know that I can do the query before echo the title attribute but I don't want to do it like that. Do you have any suggestion? or can you show me how to use that ob_start() / ob_clean() functions?
Thank you!
Shift the query to the top of the code and reuse the variables!
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title'];
?>
<html>
<head>
<?php echo '<title>', $title, '</title>'; ?>
</head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
ob_start();, in usual sense, won't help you have. However, you can use ugly solution like this:
ob_start();
echo '
<html>
<head>
<title>{title}</title>
</head>
<body>
';
$header = ob_get_clean();
// and then, when you know your title
echo str_replace('{title}', $known_title, $header);
But I strongly recommend taking another approach. You need to choose and fill the template after all data has been gathered and you know all details about which template you want. If you start echoing different parts preemptively, you will get more and more troubles. Now you need to change title for some pages. Then you will need to add css file for specific page and you will have to do that ugly business again. Why not do it the right way?

Add to page title tag based on variable from URL

I have seen the following thread but it's a bit beyond me...
How can I change the <title> tag dynamically in php based on the URL values
Basically, I have a page index.php (no php in it just named to future proof - maybe now!). It contains numerous lightbox style galleries which can be triggered from an external link by a variable in the URL - e.g. index.php?open=true2, index.php?open=true3, etc.
I would like the index.php title tag - to include existing static data + append additional words based on the URL variable - e.g. if URL open=true2 add "car gallery", if URL open=true3 add "cat gallery", if URL has no variable append nothing to title.
Can anyone assist? I have been searching but either missed the point of posts or it hasn't been covered (to my amateaur level).
Many thanks. Paul.
At the top of your php script put this:
<?php
# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');
# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');
?>
And then use this to include your custom title:
<title>Pauls Great Site<?php echo htmlentities($title); ?></title>
<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>
<?php
if( array_key_exists('open', $_GET) ){
$title = $_GET['open'];
}else{
$title = '';
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
The content of the document......
</body>
</html>
http://www.w3schools.com/TAGS/tag_title.asp
http://php.net/manual/en/reserved.variables.get.php
PHP can fetch information from the URL querystring (www.yoursite.com?page=1&cat=dog etc). You need to fetch that information, make sure it's not malicious, and then you could insert it into the title. Here's a simple example - for your application, make sure you sanitise the data and check it isn't malicious:
<?php
$open = "";
// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>
<html><head><title>This is the title: <?php $open ?></title></head>
PHP has lots of functions for escaping data that might contain nasty stuff - if you look up htmlspecialchars and htmlentities you should find information that will help.
Some of the other answers are open to abuse try this instead:
<?php
if(array_key_exists('open', $_GET)){
$title = $_GET['open'];
} else {
$title = '';
}
$title = strip_tags($title);
?>
<html>
<head>
<title><?php echo htmlentities($title); ?></title>
</head>
<body>
<p>The content of the document......</p>
</body>
</html>
Otherwise as #Ben has mentioned. Define you titles in your PHP first to prevent people from being able to directly inject text into your HTML.

Categories