John Aston
John Aston

Reputation: 127

Get data config return array

i have two php files config.php look like this:

config.php :

<?php 
return array(
   'name' => 'Demo',
   'age'  => 21,
   'job'  => 'Coder'
);
?>

in file index.php, i using file_get_contents for get data of file config.php

index.php:

$config = file_get_contents('config.php');

echo $config['name'];

but this is not working. somebody can help me?

Upvotes: 1

Views: 284

Answers (2)

dev7
dev7

Reputation: 6369

The function file_get_contents(file) reads the entire file into a string. That means that it will return a string represntation of the content of the file and NOT source code that you can just use in your main script.

  • Note: If the path to file is an absolute path, file_get_contents() will execute the php first and return the rendered output of the php file.

Since you want the source of 'config.php' to be available in 'index.php', you have to include it.

Just use include() or include_once().

config.php :

<? 
$config =  array(
   'name' => 'Demo',
   'age'  => 21,
   'job'  => 'Coder'
);
?>

index.php:

include('config.php');//or include_once('config.php');
//include makes the content of 'config.php' available exactly as if it was written inside of the document iteself.

echo $config['name'];

Hope this helps!

Upvotes: 2

Hanky Panky
Hanky Panky

Reputation: 46900

You include code and not its output.

$config = file_get_contents('config.php');

Sends your file to PHP and generates the output and then sends it back to you, which is not what you have to do for code. You have to do

$config = include('config.php'); // or require / require_once / include_once

Upvotes: 2

Related Questions