PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] PHP/Laravel - find and read 'key-value pair' from file

 February 12, 2022     file-read, key-value, laravel, php     No comments   

Issue

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;
}


Answered By - Ieuan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing