1

I am using a configuration file for something I am working on. In that configuration file, I have a line like $twelveHourTimeEnabled = true;. I want to be able to switch true to false in this but am not sure the way to change just that line from true to false.

Currently, I am using separate files that switches the two, but I know this must be grossly inefficient.

$fn = "config.php"; 
$file = fopen($fn, "w+"); 
$size = filesize($fn); 

$twelveHourConfig = "12hrconfig.php";
$twelveHourConfigFile = file_get_contents($twelveHourConfig);

fwrite($file, $twelveHourConfigFile);

fclose($file);

How would I switch the true value to false, or vice versa without requiring two other files to read in?

EDIT:

This project is a PHP plug-in for a desktop app (Alfred App for Mac OS X) which returns TV information to the user wherever they are. For this reason, this action is being done when a keyword is called. For this reason there is no way to use a database, etc.

EDIT 2: Sorry, I have no experience with JSON or other file IO operations as I normally deal with CRUD. Also, know that I have no control over the user machines, etc. This needs to function with PHP that would be installed by default when someone installs Mac OS X. Nothing more. If someone can explain JSON I would be happy to use it, I just don't know anything about it, how to use it, etc.

4

2 回答 2

1

For configuration files I would recommend the following setup.

Let's assume this is the contents of config.php:

<?php

return array(
    'opt1' => 'value1',
    'opt2' => 'value2',
);

Then, to load this configuration:

<?php

$config = require 'config.php';
// $config['opt1'] == 'value1'

Modifying the configuration can be done by changing the array and writing it back:

$config['opt2'] = 'value2 but different'; 

file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';');

To swap configuration files in your case, you could simply use copy():

copy('12hrconfig.php', 'config.php');
于 2013-03-21T00:21:54.417 回答
1

I'm not sure why you think JSON is overkill. You really only need four PHP methods for this - 2 for reading/writing files, and 2 for encoding/decoding JSON. Heck, you don't even need to understand JSON to use it as described below, but it might be nice to be able to look at the configfilename and read it, so you could learn a bit of JSON as you go ;)

The basics are let's say you have an array with your config in it, e.g.:

$configArray['key'] = 'value';

To write this out in json:

file_put_contents('configfilename', json_encode($configArray));

To read the file:

$configArray = json_decode(file_get_contents('configfilename'), true);

Note the second argument to json_decode has been explicitly set to true, so that $configArray will be an associative array. That's a personal preference; by default it'll be an object.

(This answer is based heavily on this question regarding reading/writing JSON.)

于 2013-03-21T00:32:40.850 回答