Include_once()和文件的绝对路径

时间:2014-11-05 10:44:21

标签: php include

我有以下文件:

/Index.php
/someFolder/somefile.php
/someFolder/DataBase.php
/config/config.xml

Index.php我已加入DataBase.php

include_once('someFolder/DataBase.php');

somefile.php我已加入DataBase.php

include_once('DataBase.php');

现在我想从config.xml打开DataBase.php

simplexml_load_file('config/config.xml');

如果我从config.xml DataBase.php访问Index.phpDataBase.php可以使用somefile.php,但如果我从I/O warning : failed to load external entity 执行此操作,我将其包含在{{1}}中我有一个错误:

{{1}}

如何处理?

2 个答案:

答案 0 :(得分:1)

尝试 -

simplexml_load_file('../config/config.xml');

答案 1 :(得分:1)

<?php
// resources.inc.php

define('RESOURCE_DIRECTORY', __DIR__.'/resources');

function get_resource($path)
{
    return sprintf('%s/%s', RESOURCE_DIRECTORY, ltrim($path, '/'));
}

在程序项目中,人们通常会创建一个基本配置文件,用于规范化变量或常量的路径。

使用上面的示例,您应该能够使用以下方法安全地获取资源:

simplexml_load_file(get_resource('config/config.xml'));

你可以辩论这个确切解决方案的优雅,但原则保持不变。