Using variables before include()ing them
Posted
by phenry
on Stack Overflow
See other posts from Stack Overflow
or by phenry
Published on 2010-05-14T17:20:54Z
Indexed on
2010/05/14
17:24 UTC
Read the original article
Hit count: 211
I'm using a file, page.php, as an HTML container for several content files; i.e., page.php defines most of the common structure of the page, and the content files just contain the text that's unique to every page. What I would like to do is include some PHP code with each content file that defines metadata for the page such as its title, a banner graphic to use, etc. For example, a content file might look like this (simplified):
<?php $page_title="My Title"; ?>
<h1>Hello world!</h1>
The name of the file would be passed as a URL parameter to page.php, which would look like this:
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php include($_GET['page']); ?>
</body>
</html>
The problem with this approach is that the variable gets defined after it is used, which of course won't work. Output buffering also doesn't seem to help.
Is there an alternate approach I can use? I'd prefer not to define the text in the content file as a PHP heredoc block, because that smashes the HTML syntax highlighting in my text editor. I also don't want to use JavaScript to rewrite page elements after the fact, because many of these pages don't otherwise use JavaScript and I'd rather not introduce it as a dependency if I don't have to.
© Stack Overflow or respective owner