Jump to content

[SOLVED] How do I store an array in a file for future access?


ultrus

Recommended Posts

Howdy,

I'm sifting through tons of data, and parsing it into an array. I would enjoy saving the array as a file to load again in the future, without requiring me to parse tons of data again to remake the array. Is this possible? I'm familiar with how to actually write a file, but how would I format the array/file so that it could be included in my php using "include_once" or some similar method?

 

Thank you much in advance. :)

it should be fairly simple...

<?php
        /*store the data*/
        $fp = fopen("path/to/file.txt");
        fwrite($fp, implode(',' $array));

        /*retrieve the data*/
        while($!feof($fp)){
                $line = fgets($fp, 1024);
                $array = explode($line);
        }
?>

 

something like that.

Ah! That helped a ton. Thanks to you guys, I made the following script that works great:

 

<?php

function saveArrayFile($theArray, $folder, $fileName) {

    //save data
    $fp = fopen($folder . $fileName, "w+");
    fwrite($fp, serialize($theArray));
    fclose($fp);
}

function loadArrayFile($folder, $fileName) {

//load data
$fp = fopen($folder . $fileName, "r");
$contents = fread($fp, filesize($folder . $filename));
$theArray = unserialize($contents);
fclose($fp);
return $theArray;
}

//make an array
$coolArray = array(array("hello", "howdy", "good day"), array("later", "goodbye", "cya"));

//save the array as a file
saveArrayFile($coolArray, "cache/", "data.txt");

//load the file back into an array
$reloadedArray = loadArrayFile("cache/", "data.txt");

//see what's inside
print_r($reloadedArray);

?>

 

Thank you :)

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.