简体   繁体   中英

Read an array from a php file

I have a PHP file,But data of the file is the Array .

When i open the file , i am able to get its content, but am unable to read it as an array. Its just reading as a string. Is there any way to read a php file as array.

My php file looks like,

<?php $someArray = array (
  0 => 
  array (
    'data' => 'sadsa',
    'sadsad' => 'sdsss',
    ...... 
    'DOB' => 
    array (
      0 => 
      array (
        'Day' => '12',
        'Month' => '12',
        'Year' => '12',
      ),
    ),
    ..
    ...
  ),
  1 => 
  ...........
  ...
  2 =>
  ...
  ....

Reading the file using,

file_get_contents ( '$filepath' );

Now i want to read the file and access it as an array.

You don't need file_get_contents() for the goal you intend to achieve since the file contains a declared Variable . What you need is include the file in your Current Script and access the Array as if it was declared in the same script as shown below. Remember that file_get_contents() will always return the contents of a File as a String . Ideally (in this case), this is not what you need.

<?php
    // CURRENT SCRIPT: --- PSUEDO FILE-NAME: test.php
    require_once $filepath;    //<== $filepath BEING THE PATH TO THE FILE CONTAINING 
                               //<== YOUR DECLARED ARRAY: $someArray

    // JUST AS A DOUBLE-CHECK, VERIFY THAT THE VARIABLE $someArray EXISTS
    // BEFORE USING IT.... HOWEVER, SINCE YOU ARE SURE IT DOES EXIST, 
    // YOU MAY WELL SKIP THIS PART AND SIMPLY START USING THE $someArray VARIABLE. 
    if(isset($someArray)){
        var_dump($someArray); 
    }

You are able to load the whole file as an array with the include function, you are also able to load the file with require or include.

Array file

<?php return array (
  0 => 
  array (
    'data' => 'sadsa',
    'sadsad' => 'sdsss',
    ...... 
    'DOB' => 
    array (
      0 => 
      array (
        'Day' => '12',
        'Month' => '12',
        'Year' => '12',
      ),
    ),
    ..
    ...
  ),
  1 => 
  ...........
  ...
  2 =>
  ...
  ....

Load file

<?php
$someArray = include $filepath;

You are able to include your array file too, with the include function and use the $someArray variable.

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