Is this a good method to save to all index in a variable and then echo this? for example
<?php
$txt='<!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 http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<h2>'.heaf_func().'</h2>
</div>
<div class="content">content</div>
<div class="footer">footer</div>
</div>
</body>
</html>';
echo $txt;
?>
I'd personally change your example to be like this;
<!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 http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<h2><?php echo heaf_func(); ?></h2>
</div>
<div class="content">content</div>
<div class="footer">footer</div>
</div>
</body>
</html>
Generally, no. If you need to do output buffering, just use the output buffering API. Even if you need to retrieve your output to do post-processing on it, you can do that using ob_get_contents. It won't be a big deal on most pages, but on large pages or under heavy server load you should use the output buffering support because it's better optimized for what you're trying to accomplish.
Generally, when looking at a method such as what you're contemplating, ask yourself "what does this gain me?" Your example above is clearly trivial, but unless you're planning on post-processing your results, what does it gain you?
EDIT:
I've used both the PHP-in-XML and XML-in-PHP approaches in various projects. My experience is that on a project of any significant size the PHP-in-XML (or HTML, but I try to always generate XML or XHTML) eventually turns into nasty spaghetti code that becomes a pain to maintain, whereas the XML-in-PHP approach eventually balloons into a mess of string-manipulation code that you also don't want to maintain.
Generally, I'd recommend going with an MVC (MVVM, MVP, etc. - up to you) framework for every web app, regardless of language. If applied correctly, the additionally framework complexity is more than compensated by the modularity and ease of maintenance and extensibility that you gain. If you don't feel the need or desire to target a framework (though, again, I STRONGLY recommend it), I typically follow these rules:
Whenever possible, limit PHP-in-XML to simple inclusion of values. E.g., <h1><?php echo $title; ?></h1> Try to avoid including logic in your spaghetti code (other than, perhaps, repetition, though I typically abstract that away, too).
Whenever possible, create XML documents using the XML API's instead of writing raw values to the output. XML has the advantage of being easily transformable, which in my experience is well worth the extra initial investment, at least in production apps.
Send the client an XML document representing your data with an xml-stylesheet processing instruction indicating the location of a stylesheet to apply for rendering and let the client do its own rendering. Failing that, put your data-to-presentation transformation logic in a stylesheet (XSLT, not CSS) and do the transformation server-side. I really enjoy the separation between data and presentation it allows me.
The question is why you want to do this. Just putting it in a variable and then echoing it isn't worth it but if you need to work on the string further (string replacement, etc.) it is useful.
If you're going to be doing massive multi-line text-into-variable assignments like that, consider using the HEREDOC syntax, which has the advantage of not forcing to you escape quotes, which makes the text blob far easier to read and cut/paste into other things without needing tweaks.
As for choosing if you should do PHP-in-HTML or HTML-in-PHP, it all comes down to which one would be more readable. If you have 500 lines of HTML, and only a small bit of PHP to insert, then go for PHP-in-HTML, and vice-versa. For a near even-balance, it'd come to whatever your preference is.
Related
Here is my code
<?php include('includes/header.php'); ?>
<?php
include_once "mysql_connect.php";
mysql_query("UPDATE viewcounter SET `views` = `views`+1 WHERE id='1'");
$sql = mysql_query("SELECT * FROM viewcounter WHERE id='1'");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$pagename = $row["pagename"];
$views = $row["views"];
};
?>
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Like Dislike</title>
<meta name="Description" content="Like Dislike " />
<meta name="Keywords" content=" likedislike,tk,thumbs up,thumbs down,like,dislik,love,hate,tk" />
</head>
<body>
<center>
<h1>Like/Dislike</h1>
<a href="what-should-be-here" onMouseOver="image1.src=loadImage1.src;" onMouseOut="image1.src=staticImage1.src;">
<img name="image1" src="http://www.likedislike.tk/images/left-blue.png" border=0></a>
<img src="images/logo.gif" alt="desert" width="126" height="168" align="middle" /><a href="http://www.likedislike.tk/2-justin-bieber" onMouseOver="image2.src=loadImage2.src;" onMouseOut="image2.src=staticImage2.src;">
<img name="image2" src="http://www.likedislike.tk/images/right-blue.png" border=0></a>
<br />
<?php echo ThumbsUp::item('1')->template('thumbs_up_down') ?>
<?php echo ThumbsUp::item('1')->template('mini_poll') ?>
<?php print $views; ?> views
</center>
</body>
</html>
<?php include('includes/footer.php'); ?>
Now i am confused..
where should i put this <?php include('includes/header.php'); ?>
should i put inside body or outside.
and i want to add more java script so should i load them in header.php or in the page ?
What is the best way to speed up everything and load those java script fast?
Can i load all the java script,css and some php script in header.php?
Thanks i am only 14 so don't tell me i am stupid :)
I try it and it works but i just wanted to know its right way or not.
Thanks
It seems like your code <?php include('includes/header.php'); ?> has different purpose than you assumed. It seems it is designed to deal with HTTP request headers and should be invoked before any output is sent to the browser.
You should be aware that not even a space should be sent (displayed) before header.php is executed (assuming it contains header() PHP function calls) - please see documentation.
Secondly, if you want to include JavaScript, you should do it in HTML head section or later, in the body. The way you should solve it varies depending on what you want to achieve. The best way is to combine as much JavaScript as possible in one file and compress it, do similar thing with CSS (combine all files and compress them).
By combining and compressing JS and CSS files you are making less requests to the server and less requests will be blocked (browsers have limits for concurrent requests to same domain).
Here is some documentation on including JavaScript in HTML documents: www.w3.org/TR/html4/interact/scripts.html.
JavaScript includes and additional CSS files are part of the HTML markup, and should probably be in the <head> area.
You'll typically list your PHP includes at the top of a file. The PHP is executed by the web server, and only outputs text if you use echo, print, etc. You might pick apart some WordPress themes or PHP tutorials and look at how (and pay close attention to why) people structure their markup and PHP the way they do. There's usually no right or wrong way to do things, but there are best practices to follow and the best overall layout/plan depends on what you're trying to do.
It's better to load in header is only that you need for loading page correctly. Because each
script tag will lock your page loading until this one loads. So if you have big javascripts your users will see blank page long time(minutes, maybe hours :)))).
I've been making a website with about 25 pages and every time I want to update the nav bar, or the footer, I have to go through every page and make the change!
Surely there is a way to have the header and the footer (and the side bar!) in separate documents and call them in the same way a CSS is called so they don't have to be repeated on every page.
Bonus: Is this likely to affect SEO in any way? Might it slow down the site?
Thank you,
Tara
by using include():
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Your page</title>
<style type="text/css">
<!--Your styles ect that make your page-->
</style></head>
<body>
<div class="container">
<div class="header"><?php include('./site_content/header.html');?></div>
<div class="sidebar"><?php include('./site_content/sidebar.html');?></div>
<div class="content">
your content
</div>
<div class="footer"><?php include('./site_content/footer.html');?></div>
</div>
</body>
</html>
HTML itself - ignoring framesets and iframes which do have an effect on SEO and are generally not really recommended - does not have any method to include partial HTML.
You can however use PHP (or SSI if you're oldskool) for such. It has a command to include partial files, it's called include PHP Manual.
PHP needs to be activated on your server for it. To keep this transparent you might want to map the .html file extension to PHP or use Mod_Rewrite to do that. That depends on the type of server and it's configuration.
Might it slow down the site?
The server has more work to do to process the request, therefore it slows down the site a little bit. But normally for a simple site you won't notice that much.
To prevent such, it's possible to build a simple caching mechanism on top that will convert the dynamic PHP output into static files on the fly.
I read this post and I really like this solution to templating but I am unsure of one thing. With this system wouldn't the business logic and presentation logic be in two different php files? This is all well and good as it separates them but what if there is only presentation logic as there are on some pages or what if there is a very low amount of business logic?
It seems weird that the default page the users page to will sometimes be only presentational logic and sometimes only business logic. It seems like there are two obvious solutions to this:
1) Have all default pages have business logic (even if there is none) that link to the presentational logic on a different page. The problem with this is that there are then a lot of "unnecessary" pages. The good is that it is consistent.
2) If there is no business logic for a page then just only include the presentational logic. The problem with this is that it is inconsistent when looking at filenames as to what php page includes the business and presentational logic.
Also, and this may be a little off-topic, but is there any way to template this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Website</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="styles.css" rel="stylesheet" type="text/css"/>
<link href="favicon.png" rel="shortcut icon" />
</head>
<body>
</body>
</html>
Considering I have this on every page I was wondering if there was a way to template this so the code could all be in one file and recalled.
Your templates should contain strictly presentational logic.
This means that you can include:
Loops (to print lists etc)
Conditionals (e.g. only print an element if some value is non-null)
Formatting functions (strip spaces, round numbers, etc)
A small number of template-composition helper function calls (e.g. "please include this other sub-template here")
but nothing else -- and especially not business logic! (if I forgot something important, please mention it in a comment)
Also, your templates ("views") should never be used as the target URLs that you application uses. You should have the URLs point to (possibly one of many) "controller" scripts, which then invoke the necessary business logic and pass the results to your template for display by including the template. You will find this easy to grasp if you are familiar with Model-View-Controller; if you are not, familiarize yourself first.
Finally, here's one way you could template the markup you gave:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $title;?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php foreach ($stylesheets as $stylesheet) : ?>
<link href="<?php echo $stylesheet;?>" rel="stylesheet" type="text/css"/>
<?php endforeach; ?>
<link href="favicon.png" rel="shortcut icon" />
</head>
<body>
</body>
</html>
i am new to .php. I would like to know what are all the ways we can create User Controls (How we do it in asp.net). This found with include in php, but i need to pass parameters to it and use those parameters in that php include file.
I would strongly encourage you to use a php framework for web development. Standalone php is too generic and unstructured to be effective in development.
To answer your question, if you decide to use a framework such as Symfony you will find it comes equipped to handle "User Controls" using "Partials", "Components", and "Widgets".
See http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer for more information.
--
If you decide not to use a framework, then your best bet would be to put the HTML code, in an include file (e.g. myControl.inc.php) and then include it manually in your main layout using:
Again, I'd strongly discourage anyone from developing a php application without a framework.
I remember I did an experiment to mimic ASP.NET behaviour using PHP + JavaScript.
A vague example:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict (jaFramework-Edition)//EN//"
"http://www.joelalejandro.com/ja-xhtml/ja-xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ja="http://www.joelalejandro.com/ja-xhtml/" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript" src="jaXHTML.js"></script>
</head>
<body>
<ja:MySQLServer
id="MySQL1"
ConfigFile="mysql1.conf">
</ja:MySQLServer>
<ja:Grid
id="Grid1"
UsingConnection="MySQL1"
DataSource="urminute_com.mp_songs">
</ja:Grid>
<script>
alert(window.Grid1.DataSource);
</script>
</body>
I took XHTML 1.0 Strict's definition file and added the "ja:" tags. Then, using Javascript DOM and AJAX, I replaced the tags with the content that I was required to deliver.
I don't know exactly how efficient the solution is, yet is XHTML-compliant.
Just my two cents on the subject.
Can't this be achived using "get" parameters in the include call? Something like:
include 'control.php?param1=value1';
Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.
I've been working on so many complete rewrites of a custom template engine in php for so long and so many times that i thought i'd ask for opinions.
In short, this is the most important part i have implemented so far:
Any http request is routed to handler.php
based on the requested URL a controller is instantiated and a method on that controller is called.
The controller method must return an IView compatible class instance ( IView defines a Render() method)
The template engine does some xpath for every namespace that ends in 'serverside' sprintf('//%s:*[#runat="server"]', $namespaceprefix )
For every found tag, it looks up the php class identified by $tag.localName and instantiates one and attaches it to the original template.
Once attached, the original template node is fed to the 'ServerTag' so it can initialize properly
the fully complete IView compatible instance is assigned to a temporary variable in the controller method.
The controller asks pushes data from a Model class to the view which does some nifty xpath DOM replacement.
The controller returns the completely filled view to main()the handler, which renders it.
I am basing my template on xml. a simple template currently looks like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title will be filed by the View depending on the Controller</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/" />
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo" />
</div>
<h1>www.theredhead.nl :: Test Template</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br />
<red:UserProfileLink runat="server" Username="kris" />
</div>
</body>
</html>
At current, this outputs (including the broken indentation):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Welcome to my site</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Custom/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Profile/"/>
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo"/>
</div>
<h1>www.theredhead.nl :: ModelViewController</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br/>
<div><div xmlns:profile="http://www.theredhead.nl/profile" class="ProfileBadge" style="font-size : .8em;">
<a style="text-decoration : none; border: none;" href="/Profile/View/kris">
<img style="float : left;" src="http://www.gravatar.com/avatar/5beeab66d6fe021cbd4daa041330cc86?d=identicon&s=32&r=pg" alt="Gravatar"/>
Kris
</a>
<br/>
<small>
Rep: 1
</small>
</div></div>
</div>
</body>
</html>
I've only touched on the tip of the iceberg here and yes, I will be stripping unused xmlns attributes from the output once I'm happy with the functionality
there are currently just over 200 classes in my mvc and core frameworks
I am aware there are existing solutions that can do similar things, but I want to build my own.
So the big question is: Do you have any input on must-have functionality?
P.S. if anyone is interested in the complete source-code, please leave a comment, I will be providing it on my site when I reach reasonable developer usability levels.
Why not just use PHP as your templating system. PHP IS the template system.
What is wrong with just dumping <?php=$variable;?> in an HTML template? You can use foreach loops, etc.
Just make sure that you run it from within a scope that cannot access any variables you do not want.
I have a really deep founded hate for overcomplicated template systems like this since my Java/Struts nightmares. You have to dive into namespaces, xpath, custom namespaces and all that stuff before you can change just the one thing you need.
Here's an article on templating engines: http://massassi.com/php/articles/template_engines/
You're doing it wrong.
Seems to me only Phil Reif actually read and understood the question and its intention.
Those people claiming php is the template engine and that's that are ignoring too many facts and have blinded themselves from the real world where solid frameworks are important.
So, the points must have features so far (that haven't already been implemented) are:
Lists. I'll be handling those in controls similar to <asp:DataGrid>
Validation. Will be handled with validation controls. Regular expressions, comparisons etc.
Output is forcibly valid xhtml 1.0, at least until html 5 has sinked in.
Composite custom controls (based on xml templates instead of code)
inline php code... I'm considering it, <?php ... ?> is a valid xml DOMProcessingInstruction node, but the judges are undecided.
Configurable global exception handling.
I've set the first drafts online so you might take a look and maybe get back to me with some neat ideas.
By the way things look i'll have forms up and running in the next couple days. At the moment it's only a first draft of a design (both code and style wise)
Still hoping for some more input here, what kind of controls do you people use and love? (from any framework/language)
Kris