'PHP/Laravel - find and read 'key-value pair' from file
I want to store some text informations but I don't want to use database for this. For example there is a file:
key1: some text information 1
key2: some text information 2
key3: another text information
I was wondering, what is the shortest way to find one specific value form this file using PHP or Laravel?
I could use foreach(file('yourfile.txt') as $line) {} loop to store text lines into array and then find the line with specific key, but maybe there is shorter or nicer way to do this.
Solution 1:[1]
I think you should use array instead text file
Create a new file in the app/config directory. Let's call it constants.php
In there you have to return an array of config values.
return [
'myData' => [
'key1' => 'www.domain.es',
'key2' => 'www.domain.us'
// etc
]
];
And you can access them as follows
Config::get('constants.myData');
// or if you want a specific one
Config::get('constants.myData.key1');
And you can set them as well
Config::set('myData.key1', 'test 123');
Solution 2:[2]
@leuans answer was the basis for the following function which works better for me since it also strips newlines and makes the separator configurable.
// https://stackoverflow.com/a/27917087/1497139
// getConfig('yourfile.txt','separator') returns an associative array
// example: getConfig('config.ini',': ')
function getConfig($file,$separator) {
$data = file($file);
$returnArray = array();
foreach($data as $line) {
$parts=explode($separator, $line);
$name=trim($parts[0]);
$value=trim($parts[1]);
$returnArray[$name] = $value;
}
return $returnArray;
}
Solution 3:[3]
@leuans answer is nice but this slight modification is better by:
- allowing to be have the separator character inside the value
- trimming whitespace
- ignoring blank lines
function getData($file, $separator=":") {
$data = file($file);
$returnArray = array();
foreach($data as $line) {
$line = trim($line);
$spos = mb_strpos($line, $separator);
if($spos !== false){
$key = trim(mb_substr($line, 0, $spos));
$value = trim(mb_substr($line, $spos+mb_strlen($separator)));
$returnArray[$key] = $value;
}
}
return $returnArray;
}
Solution 4:[4]
You can use the function parse_ini_file
It reads a file of name/value pairs into an array so they can be easily accessed, e.g:
$ini = parse_ini_file("data.ini");
$value = $ini['key1'];
data.ini can look like this:
; This is a comment
key1=value1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kamlesh.bar |
| Solution 2 | Wolfgang Fahl |
| Solution 3 | user151496 |
| Solution 4 | Packs |
