包括不起作用

时间:2016-01-09 17:39:19

标签: php html include

我创建了一个名为index.php的文件,在同一文件夹index.php中有一个名为"包含"的文件夹。里面是两个php文件head.php和header.php。问题是这两个文件没有包含在index.php中。现在,我已经搜索了所有堆栈溢出,我似乎无法找到答案。

<!doctype html>
<html>
<?php include 'includes/head.php'; ?>
<body>
    <?php include 'includes/header.php'; ?>
    <div id="container">
        <aside>
            <div class="widget">
                <h2>Widget Header</h2>
                <div class="inner">
                    Widget contents
                </div>
            </div>
        </aside>
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:5)

根据我对OP的评论:

  

@canthandlehtml问题现在​​是,如果您安装了Web服务器/ PHP,是否已正确配置,以及您如何访问它。您的网络浏览器为http://localhost/file.phpc://file.php in?这些是两种不同的动物。 - 弗雷德 - 伊 -

根据你的评论:

  

我确实以c://file.php的身份访问它,我不知道这可能是个问题,原谅不足之处,php对我来说是全新的

您以c://file.php而不是http://localhost/file.php访问它,这就是您的包含无效的原因。

Web浏览器不会以这种方式解析/执行PHP指令。它要求它通过安装了Web服务器/ PHP的主机运行,运行并正确配置。

旁注:

要包含的代码应“回显”某些东西,以“显示”某些东西,如果这是意图;回应HTML等。

看到<?php include 'includes/header.php'; ?>然后我认为你有一种导航菜单。

如果它包含以下内容:

<?php
    $var = "Hello world";

并且它不是“echo'd”,然后它不会显示在渲染的HTML中,它需要回显。

<?php
    echo $var = "Hello world"; // this is a valid directive
                               // it both echo's and assigns

不确定<?php include 'includes/head.php'; ?>是否包含meta,或者包含CSS等,以及它是否包含<head></head>标记。如果没有,那么你将需要添加那些,如果你包括它,或需要在头标签等的JS。

error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:只应在暂存时进行显示错误,而不是生产。

答案 1 :(得分:3)

假设网页是通过网络服务器而不是直接从文件系统访问的,那么使用/设置include_path应该有助于缓解问题(也就是说,在包含的文件中使用echo是更通常的做法!)

您可以使用文件系统路径包含文件,但如果没有网络服务器,则无法在浏览器中运行/执行php。

<?php
    /* Once the include path is set it is easy to include the file by name alone */
    set_include_path( __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR );
?>
<!doctype html>
<html>
    <head>
        <?php 
            include('head.php');
        ?>
    </head>
    <body>
        <?php 
            include('header.php');
        ?>
        <div id='container'>
            <aside>
                <div class='widget'>
                    <h2>Widget Header</h2>
                    <div class='inner'>
                        Widget contents
                    </div>
                </div>
            </aside>
        </div>
    </body>
</html>

答案 2 :(得分:0)

尝试使用

include("includes/head.php");
相关问题