Search code examples
phparraysstringtext-parsingphp-5.3

Parse var_export output text to populate an associative array


Sometime back I was getting alot of data via some API and I saved it into a flat file doing a simple var_dump or print_r. Now I am looking to process the data and each line looks like:

" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => '[email protected]', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',"

Now I need to get this data back into an array format. Is there a way I can do that?


Solution

  • What about first exploding the string with the explode() function, using ', ' as a separator :

    $str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => '[email protected]', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
    $items = explode(', ', $str);
    var_dump($items);
    

    Which would get you an array looking like this :

    array
      0 => string ''middle_initial' => ''' (length=22)
      1 => string ''sid' => '1419843'' (length=18)
      2 => string ''fixed' => 'Y'' (length=14)
      3 => string ''cart_weight' => '0'' (length=20)
      ...
    


    And, then, iterate over that list, matching for each item each side of the =>, and using the first side of => as the key of your resulting data, and the second as the value :

    $result = array();
    foreach ($items as $item) {
        if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
            $result[ $matches[1] ] = $matches[2];
        }
    }
    var_dump($result);
    

    Which would get you :

    array
      'middle_initial' => string '' (length=0)
      'sid' => string '1419843' (length=7)
      'fixed' => string 'Y' (length=1)
      'cart_weight' => string '0' (length=1)
      ...
    


    But, seriously, you should not store data in such an awful format : print_r() is made to display data, for debugging purposes -- not to store it an re-load it later !

    If you want to store data to a text file, use serialize() or json_encode(), which can both be restored using unserialize() or json_decode(), respectively.