Search code examples
phplaravelkey-valuefile-read

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

  • If all lines are in the same format ([key]: [value]) you can simply use explode(": ", $line) to get the values, and then rewrite them to a PHP array;

    // getData('yourfile.txt') returns an associative array
    function getData($file) {
        $data = file($file);
        $returnArray = array()
        foreach($data as $line) {
            $explode = explode(": ", $line);
            $returnArray[$explode[0]] = $explode[1];
        }
    
        return $returnArray;
    }