Welcome Guest, Not a member yet? Register   Sign In
How do I read/write array from text file
#1

[eluser]Leon Stafford[/eluser]
Hi,

How do I parse variables from an array in a flat file?

I have to make a quick one-page CMS with admin page and file uploads.

I have to assume the client is using the cheapest, crappiest server with no support for even SQLite, so flat files will be used.

Without flat files, I know I can do this in CI pretty fast, what I am thinking is to just adapt it to write out my data as a big array and read it back in like a CI config file.

More of a PHP question, but could someone please give me an example of writing out and reading in an array from text file?
#2

[eluser]Colin Williams[/eluser]
What's the nature of the array? Is it flat, multidimensional? Typically you would have delimited files, where each newline is a "row" of data

Code:
field1|field2|field3
field1|field2|field3
field1|field2|field3

Then you read the file into PHP, iterate over each line, then break the delimited fields into separate values

Code:
foreach ($file as $row)
{
  list($field1,$field2,$field3) = explode('|', $row);
}

Then to write to the file you just kind of do the backward operation. Delimit the fields and append them to the file.
#3

[eluser]TheFuzzy0ne[/eluser]
Another solution might be to [url="http://www.php.net/manual/en/function.serialize.php"]serialize()[/url] the data before writing it to a file, and [url="http://www.php.net/manual/en/function.unserialize.php"]unserialize()[/url] it when you read it back from the file.
#4

[eluser]xwero[/eluser]
Another way to move an array to a file is by using the var_export function.

A quick an dirty code scenario. Create a function to write the file for you
Code:
function php_array_content($file,$array)
{
   $content = '<?php'.chr(13);
  
   if(! is_array($array))
   {
      return false;
   }
   $content .= var_export($array);
  
   if (!$handle = fopen($file, 'w'))
   {
      return false;
   }
   fwrite($handle, $content);
   fclose($handle);

   return true;
}

To get the flat file content the only thing you have to do is
Code:
$cached_array = include($file);
And the array is ready to be used.
#5

[eluser]Colin Williams[/eluser]
I was thinking the flatfile was the interface for manipulating the data (or managed in Excel and exported as CSV), which ruled out using PHP or serialization. Maybe I was wrong.
#6

[eluser]TheFuzzy0ne[/eluser]
It may well be, but I read "How do I parse variables from an array in a flat file?", and instantly thought about serialization(). Perhaps I am reading too far between the lines. Hehe.




Theme © iAndrew 2016 - Forum software by © MyBB