How to set title with data from included PHP file - php

I have a website with a template page that is something like this
<html>
<head>
<title>{{TITLE}}</title>
</head>
<body>
<div id = "header"> ... </div>
<?php include 'content.php'; ?>
<div id = "footer"> ... </div>
</body>
</html>
And then content.php would look something like this
<?php
$title = "xx";
#other php code here
?>
<p> more content </p>
My question is whether there is some way to set this up so that I am able to set the title from the file included in the middle of the page (without using javascript). I know that most people suggest including it at the top but if I were to do that the html would be at the top instead of between the header and the footer. I've wracked my brains for a while and I haven't really figured out a good way to do this (and there are a variety of possible files to be included; content.php is just an example, so I really do need some way to do this dynamically). I want to avoid putting too much code outside of the template. Any ideas?

Use output buffering:
<?php
ob_start();
include 'content.php';
$content = ob_get_clean();
?>
<html>
<head>
<title><?=htmlspecialchars($title)?></title>
</head>
<body>
<div id = "header"> ... </div>
<?=$content?>
<div id = "footer"> ... </div>
</body>
</html>

I'm not sure if you're using a templating engine or not (something like Laravel's Blade templates allow for this, I believe), but assuming you are using straight PHP, I have found the most efficient way to do this is to approach from the opposite direction and include the template file in each of my content files.
For example, I may have template.php, which has multiple functions, like this:
<?php
function createHeader($title, $keywords) {
//echo or <<<EOD your header with the set variables
}
function createFooter(...) { ... } //etc
And then, in my 'child' files, I would do:
<?php include('template.php'); ?>
<?php createHeader("My Website Front Page!", "fun, good times, joy"); ?>
<h1>My page content</h1>
<p>Content goes here</p>
<?php createFooter(...); ?>
This is a different structure from what you were attempting, though, and may not retain your intended structure.

Related

php include variables without including

Can some one tell me how to "include" a variable from another .php file without all its other content.
index.php
<?php
$info=file('somedir/somefile.php');
$v1=trim($info[2]);
$v2=trim($info[3]);
$v3=trim($info[4]);
?>
the somedir/somefile.php
<?php
$variable=something;
$variable2=someotherting;
$variable3=thirdone!;
All the other content there may not be runned or showed.
?>
Can anybody please help me??
Edit:
Its for my dynamic page.
<html>
<?php
include_once 'config.php';
include_once 'includes/mysqlconnect.php';
$url_slash=$_SERVER['REQUEST_URI'];
$url= rtrim($url_slash, '/');
//$url = basename($url);
$info=file('sites/'.$url.'.php');
$title=trim($info[2]);
?>
<head>
<meta charset="UTF-8">
<title>$title</title>
<link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/reset.css">
<link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/<?php echo $theme;?>.css">
</head>
<body class="body">
<div class="container-all">
<?php include_once 'includes/header.php';?>
<div class="container">
<?php include_once 'includes/navigationbar.php';?>
<?php include_once 'includes/rightsidebar.php';?>
<div class="content"><?php
if ($url==''){
include_once "sites/home.php";
}
elseif (file_exists("sites/$url.php") && is_readable('/var/www/html/sites/'.$url.'.php')){
include_once '/var/www/html/sites/'.$url.'.php';
}
else {
include_once 'sites/404.php';
}
?></div>
<?php include_once 'includes/footer.php';?>
</div>
</div>
</body>
</html>
Hope you understand my question now.
Programming is just driving your thoughts :)
So what i want to say that your question is how you can include just some part of an included file and my answer is that you can achieve that by doing a test each time the main file is included from withing this file to see if the file is included internally or not and you can be more precise in a way that you split your main file into block which are loaded due suitable variable
Take a look for this workaround and hope you will understand what i mean
Supposing we have the main file named main.php contains that contents
<?php
echo 'I am a java programmer';
echo 'I know also PHP very well';
echo 'When the jquery is my preferred toast !';
?>
now i have three external files that will include that file each file is specific for one of this 3 programming language
So i will create my 3 files in this way :
File : java.php
<?php
$iamjavadevelopper = 1;
include_once("main.php");
?>
File : phpfav.php
<?php
$iamphpdevelopper = 1;
include_once("main.php");
?>
File : jquery.php
<?php
$iamjquerydevelopper = 1;
include_once("main.php");
?>
and my main.php will be coded in this way
<?php
if(isset($iamjavadevelopper))
echo 'I am a java programmer';
if(isset($iamphpdevelopper))
echo 'I know also PHP very well';
if(isset($iamjquerydevelopper))
echo 'When the jquery is my preferred toast !';
?>
By this way each one of our three external files will show just a part of the included file :)
The only way I can think of without cookies or session's is to make an if condition in the page.
like that:
index.php
<?php include('somedir/somefile.php');?>
the somedir/somefile.php
<?php
if ($pageName != 'somefile.php') {
$variable=something;
$variable2=someotherting;
$variable3=thirdone!;
} else {
// All the other content
}
?>
Save the variables in a separate file that can be included separately. Do it the sane way. Structure your code properly, don't try to invent solutions for problems you have because your structure is messy.

how to add standard elements in php in one line

I have created a few php files Following are their names:
standard_head.php (which contains basic standard html code)
header.php
navbar.php
sidebar.php
footer.php
standard_footer.php (which contains closing html tags)
Page content will vary in every page and would also include html content.
I am trying to create a lot of php pages which will use all of the above pages directly.
Now I can use them directly using include statement for each of them, but I was wondering if it was possible to include all of them together with one just statement ?
<?php include('../includes/standard_head.php'); ?>
<?php include('includes/header.php'); ?>
<div id="wrapper">
<?php include('includes/nav.php'); ?>
<div id="content">
<!-- my page content -->
</div> <!-- end #content -->
<?php include('includes/sidebar.php'); ?>
</div> <!-- End #wrapper -->
<?php include('includes/footer.php'); ?>
<?php include('../includes/standard_footer.php'); ?>
You could so this (note that this is a very basic example and that I wouldn't use this myself without taking into account meta tags, page titles etc.)
template.php
<?php include('../includes/standard_head.php'); ?>
<?php include('includes/header.php'); ?>
<div id="wrapper">
<?php include('includes/nav.php'); ?>
<div id="content">
<?php echo $content; ?>
<!-- my page content -->
</div> <!-- end #content -->
<?php include('includes/sidebar.php'); ?>
</div> <!-- End #wrapper -->
<?php include('includes/footer.php'); ?>
<?php include('../includes/standard_footer.php'); ?>
Then, on a page (say index.php, for example):
index.php
<?php
$content = '<h1>Welcome</h1>';
include 'template.php';
?>
P.S: If you go down this route, make sure that you check out the Output Control Functions first.
Just create a PHP file that has a list of them i.e.
<?php include("this file");
include("the other file");
?>
And then just add that file.
Not really an answer to your question, but you could use a template engine like Twig.
http://twig.sensiolabs.org/
Try using more complex template system like Smarty or some MVC framework like Zend (this is not required but would allow you to create complex sources more easily) and then build script like this:
<?php include('../includes/standard_head.php'); ?>
<?php include('includes/header.php'); ?>
<div id="wrapper">
<?php include('includes/nav.php'); ?>
<div id="content">
<?php echo $menu->getCustomEntries(); ?>
</div>
Where $menu will be your custom object containing methods for displaying menus and submenus...
There is no straight way to include multiple files, as include / require functions except only one argument. though you can use following logic.
`#include_all_files.php
include('../includes/standard_head.php');
include('includes/header.php');
...
use above file in other files
include('includes/include_all_files.php');
`

php template for different pages with different css and mysql

Hi I'm trying to figure out how to do a PHP template system with a class, i dont like header.php footer.php or smarty or whatever blabla, just want the template.html, the class.php and page1.php, page2.php etc... with my own php code, and I've found a lot of website of people teaching how to do this but i still have lots of questions.
1) i want to add EXTRA css to some pages
2) SOME pages has php code like mysql queries and stuff like that
3) the CONTENT which would be a variable where ever i want in the template is not only words, instead is a large amount of divs and stuff, also in some pages the CONTENT variable has queries inside, like fillin a (e.g)dropdown menu.
Hope somebody can guide me in this, i actually have my tempalte for explame, (the tags are just random)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<title>CompanyName | ##TITLE##</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<link href="styles.css" rel="stylesheet" type="text/css" />
##EXTRA_CSS##
<link rel="shortcut icon" href="/favicon.ico" />
<!--[if IE 6]>
<script src="DD_belatedPNG_0.0.8a-min.js"></script>
<script>
DD_belatedPNG.fix('img, div');
</script>
<![endif]-->
##EXTA_JS##
</head>
<body>
<div id="main">
<div id="container_black">
<div id="container_white">
<div id="container_header">
<div id="logo_top"></div>
<div id="lineas_verticales_top">
<div class="volver_portada">Volver a portada</div>
<div class="english_spanish"><u>EspaƱol</u> | English</div>
</div>
<div id="nav_bar_black"><div id="nav_bar_red"><div id="nav_bar_yel">
<ul class="menuholder">
<li class="menu_principal">Principal</li>
<li class="menu_empresa">Empresa</li>
<li class="menu_productos">Productos</li>
<li class="menu_clientes">Clientes</li>
<li class="menu_recetas">Recetas</li>
<li class="menu_contacto">Contacto</li>
</ul>
</div></div></div>
<div id="topbg_degr"></div>
</div>
<div id="container_left">
<div id="conmargen_left_top"></div>
<div id="container_conmargen_left_middle">
##CONTENT##
</div>
<div id="conmargen_left_bottom"></div>
<!--[IF INDEX]
<div id="fono"></div>
<div id="dir"></div>
-->
</div>
<!--[IF INDEX]
<div id="nav"></div>
-->
<div id="container_right">
<div id="conmargen_right_top"></div>
<div id="container_conmargen_right_middle">
<!--[IF PAGE OR PAGE OR PAGE]
[ELSE IF]
[ELSE IF]
-->
</div>
<div id="conmargen_right_bottom"></div>
</div>
<!--[IF INDEX]
<div id="frame_facebook">
<span>CompanyName</span> en Facebook
<div class="breakL"></div>
<fb:like href="#" layout="button_count" show_faces="true" width="100" font="tahoma"></fb:like>
</div>
-->
<br/>
</div> <!-- cierre del container white -->
</div> <!-- cierre del container black -->
<div id="footer">
<div class="footer_comment">
CompanyName Todos los derechos reservados 2011
</div>
</div>
</div> <!-- cierre del main -->
<br/>
</body>
</html>
for instance contact.php, the content would be a form, and on the top of the page i have this huge php code, where i validate and all.
I'd really appreciate if somebody would put me in the right path to do this. thank you in advance.
There are probably a hundred different ways you could approach this, each with their own advantages and disadvantages - using databases and/or ajax calls and/or headers and footers as you already said. You really have to work out which way works best for your particular project or style of coding, or both.
However - if you really just want 'template.html', but have some pages with PHP, javascript, MySQL or whatever else in them - then I would suggest.
Create template.html with placeholders such as {PAGE_TITLE}, {MAIN_CONTENT} or whatever you need.
Create page1.php/page2.php etc and do any server side work, generate variables to match your placeholders. It might be handy to store them as an array, ie:
PAGE_VARS array(
['TITLE'] => My Page
['CONTENT'] => This is my page content
)
At the end of your 'page' script, load the entire contents of template.html into a string
$template = file_get_contents('template.html')
Then, build up your template with the replaced variables using either a basic loop:
foreach ($PAGE_VARS as $KEY=>$VALUE) {
$template = str_replace("{".$KEY."}",$VALUE,$template)
}
(Feel free to get clever and probably more efficient with some regular expressions above, this is just a quick example.)
Output your template.
echo $template;
You can create a quick class (class.php) like this that will be your 'template engine' :
class Template {
var $contents;
function load($file) {
if ($fp = fopen($file, "r")) {
$this->contents = fread($fp, filesize($file));
fclose($fp);
}
}
function replace($str,$var) {
$this->contents = str_replace("<".$str.">",$var,$this->contents);
}
function show() {
$search = array(
'/\t/', //Remove Tabs
'/<!--[^\[-]+?-->/', //Remove Comments
'/\n\n/' //Remove empty lines
);
$replace = array(
'',
'',
''
);
$this->contents = preg_replace($search, $replace, $this->contents);
echo $this->contents;
}
}
In your template.html file, add special tags where you want to put your content, like this :
<html><head></head>
<body>
<div id="id1"><page_title></div>
</body>
</html>
...
Then create a function to write inside the tags (one per zone) :
function writetitle($s) {
$GLOBALS['writes']++;
$GLOBALS['page_title'] .= $s;
return;
}
finally, in your page.php, call the class, write your content, and generate the page :
require_once('class.php');
//Load Class
$template = new Template;
$template->load("template.html");
//Some query :
$query = mysql_query('SELECT...');
$res = mysql_num_rows($query);
//write your content :
writetitle('my title, '.$res.'');
//Generate the page :
$template->show();
Doing this you can create as many zones as you want. writetitle act like echo, so you can make queries and everything you want.
I hope it helps.
Insetad of having PHP parsing your template files I would suggest writing the templates using PHP and not your own pseudo code.
It's perfectly valid to write
...
<body>
<?php if($fooBar == "hahahaha"):?>
The cool foobar link
<?php endif;?>
</body>
...
I would then create a layout file with all common html etc. Then using small template snippets to be inserted into the layout where the main content goes.
By having actual PHP code in your templates the PHP enginge can handle them and you don't have to write your own logic to handle loops, if statements etc.
Take a look at Zend Framework and you'll get a good idea of how you can write your template engine.

How do I insert an HTML page using PHP?

I wanted to know, is there any way to insert an HTML page into PHP without using the include function? I do not want to use an external html file, I want to write the html coding directly into the php coding.
Thanks for your help!
Interleave it:
<?php
// Some php code.
?>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>Header</h1>
<?php /* More php code. */ ?>
<p>Blah!</a>
</body>
</html>
<?php /* Even more php. */ ?>
From a best practices point of view, though, avoid doing this - having business logic (PHP) and presentation (HTML) in the same place makes maintaining harder.
EDIT: To address your comment. You can either do it the same way, or use echo:
<?php if (x == 5) { ?>
<p>Blah!</a>
<?php } else {
echo '<p>Bleh</p>';
} ?>
If you need to include snippets of HTML based on conditions, you can interleave code like this. In this case it's convenient to use the alternative syntax for loop controls
<?php if ( $var ): ?>
<html>
<title>YAY</title>
</html>
<?php endif; ?>
so the code is clearer to read and you retain HTML syntax coloring (if your editor supports it).
It is very bad habit to mix HTML and PHP (for more than just output control), but here you go:
$html = "<div>This is HTML</div>"
echo $html;
or Heredoc syntax:
$html = <<<EOF
<div>
<p>
Some longer HTML
</p>
</div>
EOF;
echo $html;
or using alternative syntax for control statements if the output depends on some condition (or if you loop through an array etc.)(which is far better than building HTML with strings):
<?php if($foo): ?>
<div> Some HTML output </div>
<?php else: ?>
<div> Some other HTML </div>
<?php endif; ?>
or just
<?php //PHP here ?>
<div>HTML</div>
<?php //more PHP ?>
<div>more HTML</div>
<?php //even more PHP ?>

How should components add JavaScript and CSS in Symfony

My layout.php calls include_javascripts() before my componet could call sfResponse::addJavascript(). Is there a "helper" or a "best practice" to handle this?
Do I have to Seperate the call sfResponse::addJavascript()? I were happy to avoid it.
Here ist my actual workaround:
<head>
<?php $nav = get_component('nav', 'nav') /* Please show me a better way. */ ?>
<?php include_javascripts() ?>
...
</head>
<body>
<?php /* include_component('nav', 'nav') */ ?>
<?php echo $nav ?>
...
</body>
Thanks
From: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer
File Inclusion Configuration
// In the view.yml
indexSuccess:
stylesheets: [mystyle1, mystyle2]
javascripts: [myscript]
// In the action
$this->getResponse()->addStylesheet('mystyle1');
$this->getResponse()->addStylesheet('mystyle2');
$this->getResponse()->addJavascript('myscript');
// In the Template
<?php use_stylesheet('mystyle1') ?>
<?php use_stylesheet('mystyle2') ?>
<?php use_javascript('myscript') ?>
If your component is always used just move your javascript inclusion into the layout's rendering in your app's view.yml:
default:
javascripts: [my_js]
There is no need to separate the JS call when it is always used.
UPDATE:
If you must maintain the JS inclusion with the component you can place your component call in a slot before your include_javascripts() call to add it to the stack to be rendered and then include the slot in the appropriate place:
<?php slot('nav') ?>
<?php include_component('nav', 'nav'); ?>
<?php end_slot(); ?>
<html>
<head>
<?php include_javascripts() ?>
...
</head>
<body>
<?php include_slot('nav'); ?>
<?php echo $nav ?>
...
</body>
</html>
You may have to disable the sfCommonFiter which is now deprecated. The common filter automatically adds css / js into the layout.
Once you have done this, you can move the include_javascripts call anywhere within the layout.php file, below the include_component('nav', 'nav') call

Categories