Reading from Text File into an Array in PHP

Discussion in 'Web Design and Development' started by kolax, Aug 6, 2012.

  1. kolax macrumors G3

    Mar 20, 2007
    I have a drop down list as part of an HTML form. I'm using a PHP array to store each option and then loop it to populate the list. It works fine, but the drop down list options may change over time, and I want a quick way for other people to edit them.

    So it'd be better if I had a plain text file with:

    Option 1
    Option 2
    Option 3

    And then load that into an array in PHP, and using my current code it should all work.

    However, each time the form is refreshed, that text file would be read again. Are there any performance issues or glitches with that? The server is more than capable.

    Finally, if it seems a good way to go, I've found some basic PHP examples of reading text from a file, but not in the way I'm after - when a line ends, that's the end of a variable. I'd rather have nothing in the text file but the list options (no new line characters etc).
  2. graemenail macrumors newbie


    Jun 15, 2012
    Read from your plain-text file to some variable, then use explode() on that variable with the delimiter set as the new line character. This will give you the array you currently have.

    Then I'm assuming you use a loop to echo the option tags around each value. Rather than echo each value '<option>Option 1</option>'; simply write it to a new file (processedOptions.txt or whatever).

    You'll end up with a file that looks like:
    <option>Option 1</option><option>Option 2</option>...

    Now use php to include this new file in your HTML.
    This way you only process the plain-text list once and create a cache of it.

    You only need to do this once (until you update your plain text file). So your code must check for the existence of this processed file, and determine if it is older than the plain-text file. If it does not exist, or is older than your plain-text file, then you need to go through the steps above. If it exists, and is not older than your plain-text file all you need do is include it.

    Hope this makes sense.

Share This Page