开发者

How to send data to a previously included PHP file?

I have a header.php and a footer.php file. My HTML header is in header.php and I have an index.php file.

I’m using so (index.php):

require 'header.php';

$example_code = 'example';

︙

require 'footer.php';

And my header.php:

<html>
 <head>
  <title>
     ???
  <title>
  <meta name="description" content="???" /> 
   <meta nam开发者_如何学JAVAe="keywords" content="???" /> 
 </head>
<body>
︙

I want to send some data from index.php to header.php to print it there (see the ???). I’m thinking of the header() function but I can’t see any example in the PHP manual.


The best thing you could do is separating logic from presentation. Using an MVC approach, where you take care of all logic in one file, and then display the outcome of what you've done in a presentation only layer.

Besides that, if you want to keep your approach, what you simply have to do is to make assignments before header.php is included. So, suppose you want to change your page title, this is what you need to do:

index.php

<?php
$title = 'My Page Title';
$description = 'My meta description';
$keywords = 'keyword list';
include('header.php');

?>

header.php

<html>
 <head>
  <title>
     <?php echo $title; ?>
  <title>
  <meta name="description" content="<?php echo $description; ?>" /> 
   <meta name="keywords" content="<?php echo $keywords; ?>" /> 
 </head>
<body>

It's as simple as that. Just keep in mind you can't make assignments to a page/script, AFTER such has been included

Again, though, I'm trying to answer you, not necessarily suggesting this approach. If your application has just a couple of pages, that's ok. If it's bigger (or going to be), something like the MVC pattern (two-step view pattern) is a better alternative IMHO.


php header function got nothing to do with html tag "head" .


<?php

 $tpTitle="Helping you to improve your web site";

  $pgHeading="Site-Report.com - Helping you to improve your web site";

  $pgDesc="Helping you to improve your web site";

 $pgKeywords="site-report";

  ?>


<head>

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>

 <title><?php echo $tpTitle ?></title>

 <meta name="description" content="<?php echo $pgDesc ?>"></meta>

 <meta name="keywords" content="<?php echo $pgKeywords ?>"></meta>

</head>



 http://www.cre8asiteforums.com/forums/index.php?showtopic=4558


The header() function is not suitable for what you would like to do. You're merely looking for a variable:

index.php:

$title = 'My Page Title!';
$description = 'This is how I describe it.';
$keywords = 'page, title, describe';

header.php:

   <title>
      <?php echo htmlspecialchars($title); ?>
   <title>
   <meta name="description" content="<?php echo htmlspecialchars($description); ?>" /> 
   <meta name="keywords" content="<?php echo htmlspecialchars($keywords); ?>" /> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜