【问题标题】:Include path in PHP在 PHP 中包含路径
【发布时间】:2014-05-08 22:21:39
【问题描述】:

这是我的文件夹和文件:

文件夹主要 文件夹 a -fila.php 文件夹 b - 文件 b.xml 文件夹 c - 文件 c.php 索引.php

当我尝试这样做时,它会显示任何建议或修复错误。

文件 c.php

<?php
class Abc{
public function __construct(){
    $xml = simplexml_load_file('b/b.xml');
}}?>

所以我在 a.php 中包含文件 c.php,它会显示错误

<?php require '../c/c.php'; $abc = new Abc(); ?>

文件索引.php

<?php
   require 'c/c.php';
   $abc = new Abc();
 ?>`

但如果我包含在 index.php 中,则没有问题。如何修复 c.php 中的路径('b/b.xml'),以便可以将其包含在项目的任何位置。


我找到了修复它的方法。通过这样做

文件 c.php

$xml = simplexml_load_file(dirname(dirname(__FILE__)).'/b/b.xml');

文件 a.php

include dirname(dirname(__FILE__)).'/c/c.php';
$abc = new Abc();

在文件 index.php 中

require dirname(__FILE__).'/c/c.php';
$abc = new Abc();

【问题讨论】:

    标签: php path include absolute-path


    【解决方案1】:

    你可以修改c.php如下:

    <?php
    
         class Abc
            {
                public function __construct()
                   {
                     $xml = simplexml_load_file('mainfoldername/b/b.xml');
                   }
            }
    ?>
    

    【讨论】:

      【解决方案2】:

      这是在 Joomla / Wordpress / Cakephp 和其他开源中使用的简单想法。

      在您的 index.php 中,使用:

      require(dirname(__FILE__).'/c/c.php');

      在类构造中,使用:

      $xml = simplexml_load_file(dirname( __ FILE__ ) .'/b/b.xml');

      让我知道这是否有效。

      谢谢, 蒙贾尔

      【讨论】:

      • 我在 index.php 没有遇到任何问题。问题是当我运行 a.php 文件时。
      • 只需使用 dirname( __ FILE__ )(它是一个 PHP 系统变量)来检索当前文件夹路径。
      • 它不工作我回显文件部分我得到这个:/home/u210663092/public_html/main/c/b/b.xml 我想删除 c 目录..
      • 当前文件夹路径是 /home/u210663092/public_html/main/c 但我将文件夹 b 中的文件包含到文件夹 c 文件中..
      • 好的。为此,您可以在配置文件中使用另一种简单的方法(基本上在 OPENCART / ZENCART / OSC 等中使用),使用定义变量并在包含时调用它,例如定义(DIR_MAIN,'/home/u210663092/public_html/main');请让我知道这是否更好:)
      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2013-11-09
      • 2014-05-19
      相关资源
      最近更新 更多