Hi guys,

I'm trying to write some code that saves info to text files instead of a database. (i cannot use a database for this project).

I have an array like this:

<?php

$person = array(
	"Title" 	=> "Mr",
	"FirstName"	=> "James",
	"SurName"	=> "Bond",
	"Age"		=> "38"
);

?>

But sometimes some fields may not be there - such as "Age", or "title". So i cannot use a for loop, as when it reads it back, it will not be the same length.

I have tried saving it to a file with $save = print_r($person,true);
But then cannot find a way to re-read the saved data from the print_r

Any help would be amazing, cheers!

    Thanks niroshan -- i will try it now and see if it works.

    Thanks for the fast reply πŸ™‚

      I recommend
      [man]file_put_contents[/man]
      [man]file_get_contents[/man]
      ... for read and write to file.
      They are dead easy to use! πŸ™‚

      Example:

      <?php
      
      $filename = 'mydbfile.txt';
      
      $mydata_array = $person = array(
      	"Title"     => "Mr",
      	"FirstName" => "James",
      	"SurName"   => "Bond",
      	"Age"       => "38"
      );
      
      
      //make array into a string of data, serialized
      $data = serialize($mydata_array);
      //write data string
      file_put_contents($filename, $data);
      
      
      //read back data string
      $data = file_get_contents($filename);
      //unserialize string of data into array format
      $newperson_array = unserialize($data);
      
      //Have a look at result!
      echo '<pre>';
      var_export($newperson_array);
      
      ?>
        itsallgood wrote:

        (i cannot use a database for this project)

        Are you sure? SQLite is a SQL database of sorts that has no "server" portion - it's just a client (e.g. the PHP extension) and text files that the client stores/retrieves data from.

        Otherwise, you could either follow the serialization suggestion above, or use a CSV format. If you setup a sort of "header" array that contains all of the possible columns that the data may or may not have, you can use it to insert default values. Example:

        $header = array(
            "Title"     => "Unknown",
            "FirstName" => "",
            "SurName"   => "",
            "Age"       => 0
        );
        
        $mydata_array = array( 
            "Title"     => "Mr", 
            "FirstName" => "James", 
            "SurName"   => "Bond", 
            // Age omitted
        ); 
        
        $data_to_insert = array_merge($header, $mydata_array);

          Cheers for all the help guys -- these examples are great. I will try them all πŸ™‚

          bradgrafelman -- i have to admit i'd never heard of sqlite :o - So i will also look into that.

          Can i just ask your opinions...

          The site i am working on get's over 100k hits a day. Would there be any problems with using text files and fread/fopen to store the data? Would sqlite be better?

          Do i really need to use a mysql database? I would if i absolutely needed to. I just do not know how a database would work. (With no fixed fields or length)

          The same query would be called every time - so if it could cache the query.

          I now know how to do all the above -- but i do not know which is for the best.

          Cheers again guys.

          (I'm sorry the above doesnt really make much sense - i may have a think how better to explain myself and open a seperate post - cheers)

            I honestly would recommend you use a full DBMS (such as MySQL) for something like that. It's hard to just jump in and learn SQL in a short amount of time - it takes a lot of reading and experience, IMHO. I'm sure there are plenty of us here that would gladly help you design your first database, though, so you could learn how it goes.

              Ultimately, they all read/write data from the disk (or cache memory) whether you're using a text file or a DBMS. The advantage of a database (whether SQLite or MySQL) is the power and flexibility of a good DBMS, plus the fact that they are optimized to perform most common data search/retrieval tasks more efficiently than your PHP code likely could using a text file. The DB also tends to be more robust than using flat files, as it's less prone to accidental deletion or overwriting, and a DB will have built-in locking mechanisms you can use to prevent race conditions by concurrent user requests should that be an issue (not that you can't do file locking too, should you want to go that route, though again it may not be as robust).

                I still remember back in my University days where database is specifically NOT to be used. You may have guessed it. It is for my 3rd year final project. The professor wanted something light and so text files was the way to go, not to mention during that time database cost license monies.

                That was at least 12 years ago and now currently I believe FREE database should be brought to those Professor attention. Open Source movement has progressed A LOT for the past decade πŸ™‚

                Anyone know who triggered this Open Source movement into momentum? I believe it was due to the Apache Web Server project ? Sorry for diverting from PHP topic.

                  Open Source has been around a lot longer than that. Before it was commercialised in the 1980s, Unix was open source. Even after that, there were plenty of clones and rewrites for people to hack on.

                  There has been the FSF and the GNU project since 1982 or so.

                  And of course Linux, starting in 1991 - less than a year after private companies were allowed to sell public access to the Internet.

                    If anyone can look at the following. This is what i have:

                    It's just separate txt files holding a single array. Every array key could be different depending on the file, except for the β€œcreated” one, which is older than 30 days – the file is deleted.

                    The code i am using to read the files is:

                    Save the file:

                    $output = http_build_query($text, 'flags_');
                    $fd = fopen($page, 'w');
                    fwrite($fd, $output);
                    fclose ($fd);
                    unset($output);	
                    

                    Save the file:

                    $page = $_GET['page'];
                    $fd = fopen($page, "r");	
                    $data = fread ($fd, filesize ($page));
                    fclose ($fd);
                    parse_str($data, $newArray);
                    //$newArray now contains what is used in the template.
                    // IF $newArray[β€˜Created’] is over 30 days ago – delete the text file -- and tell user their temp page has gone.
                    

                    So every page load will just be loading the text file - no saving to the file, not queries, just loading the whole contents. If the last item in the array is older then 30 days -- it is removed, and the user is told it is gone.

                    The only way i can think of doing the above with a database is the following table:

                    PAGE
                    ARRAY
                    CREATED

                    As the fields are not the same, i couldnt have seperate ones for "NAME, AGE, ETC".

                    If no other queries are performed - would it still be better to use a mysql database? Usally when the same queries are done over and over, you would cache the query -- which would take it back to just loading txt/xml files again anyway.

                    Thanks for the help πŸ™‚

                      Write a Reply...