parsing strings

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
darnoobie
Forum Newbie
Posts: 1
Joined: Mon Dec 26, 2011 11:35 pm

parsing strings

Post 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
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: parsing strings

Post 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;
    }
  }
?>
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: parsing strings

Post 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
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply