【问题标题】:How to read an array from another php page如何从另一个php页面读取数组
【发布时间】:2013-06-18 14:01:16
【问题描述】:

我将下面提到的代码(实际上是配置)写在一个文件(config.php)中,我想将 config.php 中写的内容放在另一个文件(check.php)中

config.php 中编写的代码:

<?php
$CONFIG = array (
  'id' => 'asd5646asdas',
  'dbtype' => 'mysql',
  'version' => '5.0.12',
);

check.php中用来获取内容的代码是:

$config_file_path = $_SERVER['DOCUMENT_ROOT'] . 'config.php';
$config = file_get_contents($config_file_path);

使用上面的代码,我得到了一个字符串的输出,我想把它转换成一个数组。为此,我尝试了以下代码。

$config = substr($config, 24, -5); // to remove the php starting tag and other un-neccesary things

$config = str_replace("'","",$config);
$config_array = explode("=>", $config);

使用上面的代码,我得到如下输出:

Array
(
    [0] =>   id 
    [1] =>  asd5646asdas,
  dbtype 
    [2] =>  mysql,
  version 
    [3] =>  5.0.12
)

这是不正确的。

有什么办法可以把它转换成数组。我试过 serialize() 以及 accessing array from another page in php 中提到的,但没有成功。

对此的任何帮助将不胜感激。

【问题讨论】:

标签: php arrays file


【解决方案1】:

使用 include 或 require 来包含和执行文件。不同之处在于文件不存在时会发生什么。 inlcude 会抛出警告,require 会抛出错误。 为了确保第一次加载(并执行)文件,您还可以使用include_oncerequire_onephp.net 如果您无法包含该文件(有什么原因),请查看 eval() function 以从字符串执行 php 代码。但出于安全原因,完全不建议这样做!

require_once('config.php');
include_once('config.php');
require('config.php');
include('config.php');

【讨论】:

    【解决方案2】:

    你不需要file_get_contents:

    require_once 'config.php'
    var_dump($CONFIG);
    

    【讨论】:

      【解决方案3】:

      您怎么会看不懂require_once 指令? :)

      $config = file_get_contents($config_file_path);
      

      必须是:

      require_once $config_file_path;
      // now you can use variables, classes and function from this file
      var_dump($config);
      

      如果您点击链接to the require_once manual page,请同时阅读includeinclude_once。作为一名 PHP 开发人员,您必须了解这一点。这是初级的

      【讨论】:

        【解决方案4】:

        如果你使用codeigniter不需要包含配置文件,你可以使用$this来访问,但是如果你使用普通php,你需要使用include()或者require()或者include_once()或者require_once()

        【讨论】:

        • 是的,我正在使用 codeigniter,但 config.php 文件位于框架之外。我会试试你的建议。
        【解决方案5】:

        如果您这样做,我对您的方法感到非常困惑:

        include(config.php);
        

        然后您的 $CONFIG 变量将在其他页面上可用。

        print_r($CONFIG);
        

        看看PHP website which documents the include function

        【讨论】:

          【解决方案6】:

          简单

          include_file "config.php";
          

          【讨论】:

          • 哦,是的...我真的忘记了这种方法。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-01-25
          • 2011-01-26
          • 2015-02-28
          • 2015-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多