Jump to content

php singleton class to read multidimensional array from txt file


user12345

Recommended Posts

I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved.

 

This is what I have tried so far:

 



    class singleton {
    
        protected static $instance = null;         
    
        public static function getInstance() {
            if (!isset(static::$instance)) {
                static::$instance = new static;
            }
            return static::$instance;
        }
        public static function flattenArray($array) {
      
            $return = array();
                    
            $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    
            foreach ($iterator as $value) {
                $return[] = $value;
            }
            return $return;
        }
    
        public static function loadFile($path) {
    
            $file_handle = fopen($path, "r");
    
            while (!feof($file_handle)) {
    
                $line = fgets($file_handle);
    
                $rawarray[] = $line;
            }
    
            $flattedarray = self::flattenArray($rawarray);
                
            fclose($file_handle);
            return $flattedarray;
        }


 

    

With the txt file containing:

 

    array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')

 

I run the class with: 

 



    include 'singleton.php';
    
    $singleton = singleton::getInstance();
    
    $flattedarray = $singleton->loadFile("file.txt");
    
    echo '<pre>';
    print_r($flattedarray);
    echo'</pre>';


 

I get as a result:

 



    Array
    (
        [0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g')
    )


 

Which is the same array found in the txt file.

 

how can i do it without using eval.

 

What am I doing wrong ?

PHP will not read the text file as PHP code. It will see it as just plain text.

 

If you need to save an array to a flat file, you should either serialise it or json_encode it. You then use unserialize or json_decode to read the array back into PHPs memory.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.