0

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.

3
  • 2
    You would need to include or require or what have you. Commented Dec 2, 2016 at 6:22
  • 2
    use include instead Commented Dec 2, 2016 at 6:22
  • 2
    php.net/include Commented Dec 2, 2016 at 6:24

2 Answers 2

1

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); 
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.