Page 1 of 1

parsing strings

Posted: Mon Dec 26, 2011 11:54 pm
by darnoobie
Hello forum, I'm here looking for some help. I've searched through the internet looking for how to parse a config file. I have a file that looks like the following:
MAX_PLAYERS = 100
ENABLE_SPELLS = TRUE

I would like to read this from a file named test.cfg and set the values into variables. So far I have this :

Code: Select all

<?php

$file = fopen("test.cfg","r");
if(file != NULL)
{
    while(!feof($file))
         {
             $line = fgets($file);
             //im stuck here on parsing it
         }

}
?>
Im able to get the strings, but unable to parse the string into getting the data and setting it into the variables $MAX_PLAYERS and $ENABLE_SPELLS

Re: parsing strings

Posted: Tue Dec 27, 2011 12:07 am
by twinedev

Code: Select all

<?php
  // list of variables you want to make SURE the config cannot write to
  $aryBlock = array('GLOBALS','_POST','_GET','_SERVER','_SESSION','_COOKIE','aryBlock');

  // Do the rest of this for each line, however you are loading them in ($strLine would be one single like)
  list($varName,$value) = explode('=',$strLine,2);
  $varName = trim($varName);
  if (!in_array($varName,$aryBlock)) {
    if (strtolower($value)=='true') {
      $$varName = TRUE;
    }
    elseif (strtolower($value)=='false') {
      $$varName = FALSE;
    }
    else {
      $$varName = $value;
    }
  }
?>

Re: parsing strings

Posted: Tue Dec 27, 2011 12:14 am
by s.dot
Looks like ini style syntax.

Try:

Code: Select all

$settings = parse_ini_file('test.cfg');
print_r($settings);
Then you can access the array, such as

Code: Select all

echo $settings['MAX_PLAYERS']; //prints 100