简体   繁体   中英

How to read an array from another php page

I have the below mentioned code (actually, configuration) written in a file (config.php) and i want to get the content written in config.php in another file (check.php)

Codes written in config.php:

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

Code written in check.php to get the content is:

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

Using the above code i am getting the output as a string and i wanted to convert it into an array. To do so, i have tried the below code.

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

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

Using the above code, i am getting an output like:

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

which is incorrect.

Is there any way to convert it into an array. I have tried serialize() as well as mentioned in accessing array from another page in php , but did not succeed.

Any help on this will be appreciated.

I'm very confused at your approach, if you just do this:

include(config.php);

Then your $CONFIG variable will be available on other pages.

print_r($CONFIG);

Take a look on the PHP website which documents the include function .

You don't need file_get_contents :

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

Use include or require to include and execute the file. The difference is just what happens when the file doesn't exist. inlcude will throw a warning, require an error. To make sure just to load (and execute) the file the first time you can also use include_once , require_one php.net If you are somehow not able to include the file (what reasons ever) take a look at the eval() function to execute php code from string. But this is not recommendet at all because of security reasons!

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

简单

include_file "config.php";

How could you fail to read about the require_once directive? :)

$config = file_get_contents($config_file_path);

Must be:

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

If you follow the link to the require_once manual page please read also about include and include_once . As a PHP developer you MUST know about this. It's elementary

如果使用codeigniter不需要包含配置文件,则可以使用$ this进行访问,但是如果使用的是纯PHP,则需要使用include()或require()或include_once()或require_once()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM