1

I have a text file that contains a list of arrays:

'1920s' => array('20s','twenties')
'1930s' => array('30s','thirties')
'1940s' => array('40s','forties')
'1950s' => array('50s','fifties')

I want to import it as an array of arrays, like this:

Array
(
    [1920s] => Array
        (
            [0] => 20s
            [1] => twenties
        )

    [1930s] => Array
        (
            [0] => 30s
            [1] => thirties
        )

    [1940s] => Array
        (
            [0] => 40s
            [1] => forties
        )

    [1950s] => Array
        (
            [0] => 50s
            [1] => fifties
        )

)

I import the file:

$decadesFile = file_get_contents('/Users/derwood/capsule/decades.txt');
$decades = explode("\r",$decadesFile);

But I get an array of lines of text:

Array
(
    [0] => '1920s' => array('20s','twenties')
    [1] => '1920s' => array('20s','twenties')
    [2] => '1940s' => array('40s','forties')
    [3] => '1950s' => array('50s','fifties')

Is there another combination besides "file_get_contents" and "explode" I should be using?

Edit: I indeed read the answer listed, but the text file is being generated by a FMP database, not print_r output, so with my limited experience I didn't think the question was a duplicate. However, the linked question and the answers here are all very helpful in illustrating how they are related. Thank you.

3 Answers3

1

I am sure regex on each line could have been a better solution but for the sake of using explode and assuming contents of file are in $file

$lines = explode("\n",$file);
foreach($lines as &$line){
    $line = explode("'",$line);
    $output[$line[1]][0] = $line[3];
    $output[$line[1]][1] = $line[5];
}
unset($lines);
var_dump($output);
georoot
  • 3,557
  • 1
  • 30
  • 59
0

print_r function is not good function to save array. Use json_encode or var_export.

See print_r_reverse function of : Recreate original PHP array from print_r output

function print_r_reverse($in) {
    $lines = explode("\n", trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}
Community
  • 1
  • 1
user2226755
  • 12,494
  • 5
  • 50
  • 73
0

What you are talking about in programming lingo is "data serialization"

https://en.m.wikipedia.org/wiki/Serialization

Most mature programming languages give the means of serializing data types so they can be stored ( a file, memory, cache server etc ) and recreated at a later time and even on a different server.

You should use php's serialize method to save the data to file and unserialize to bring the data back into scope

http://php.net/manual/en/function.serialize.php http://php.net/manual/en/function.unserialize.php

You could use json as well, but it's limiting in what it can do compared to using PHP's built in serializing engine

John
  • 912
  • 6
  • 12