doukun8670 2014-04-10 20:19
浏览 15

PHP - 如何在包含之前包含php脚本而不运行它

In my file index.php I have included this text from another file.

<title>
  <?php

  $title = "";
  if (basename(__FILE__, ".php") == "index") {
    $title = "Home";
  } else {
    $title = ucfirst(basename(__FILE__, ".php"));
  }

  echo $title;
  ?>
</title>

And I guess you can see what i does, and if not, then it's supposed to set the title to the basename of the file. So say you have a file called downloads.php, then the title with this script would be Downloads. But I have this problem which I don't know how to get past. When I include the text via.

<head>
  include "filename.php";
</head>

And my problems is when I include the text, the 'script' runs before it includes. Say if the name of the file you included is filename.php and the main page where you have included the text is main.php, the header would be Filename and not Main. And the reason why I want to include the text, and not just paste directly into main.php is because it's much easier to edit if you have multiple files where you need the exact same code.

I hope you understand what I'm asking, and that you are able to help me.

  • 写回答

2条回答 默认 最新

  • duangai1941 2014-04-10 20:28
    关注

    It looks like you're trying to set up a simple system for breaking your pages up into "subpages". Good idea. But rather than relying on the filename, why don't you set a variable? For example:

    In page_title.php:

    <?php
    echo "<title>" . $title . "</title>";
    

    In index.php:

    <?php $title = "Home"; ?>
    <head>
        <?php include "page_title.php"; ?>
    </head>
    

    In some_other_page.php:

    <?php $title = "Some Other Page"; ?>
    <head>
        <?php include "page_title.php"; ?>
    </head>
    

    And the same for any other pages you want...

    In fact, you probably want to encapsulate the whole <head></head> section of your page.

    Finally, rather than reinventing the wheel, you might want to look at some of the templating engines out there for PHP. I like Smarty, but there are others. These templating engines make it possible to write template files (including other template if necessary) and make it easy to simply pass variables to the template & render your HTML.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算