douhuangzhi0707 2011-08-13 10:13
浏览 39
已采纳

如何将数据发送到以前包含的PHP文件?

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 name="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.

  • 写回答

4条回答 默认 最新

  • dseax40600 2011-08-13 10:25
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)