Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php retrieve data from text file

Tags:

php

Imagine I have a certain text file like this:

 Welcome to the text file!
 -------------------------
 Description1: value1
 Description2: value2
 Description containing spaces: value containing spaces
 Description3: value3

Storing this data into a text file would be easy, like this:

 $file = 'data/preciousdata.txt';
 // The new data to add to the file
 $put = $somedescription .": ". $somevalue;
 // Write the contents to the file, 
 file_put_contents($file, $put, FILE_APPEND | LOCK_EX);

With a different description and value every time I write to it.

Now I would like to read the data, so you would get the file:

 $myFile = "data/preciousdata.txt";
 $lines = file($myFile);//file in to an array

Lets say I just wrote "color: blue" and "taste: spicy" to my text file. I don't know on which lines they are, and I want to retrieve the value of the "color:" description.

Edit Should I let php "search" though the file, return the number of the line that contains the "description", then put the line in a string and remove everything for the ":"?

like image 350
Mdlc Avatar asked May 20 '26 23:05

Mdlc


2 Answers

With explode you can make an array containg the "description" as a key and the "value" as value.

$myFile = "data.txt";
$lines = file($myFile);//file in to an array
var_dump($lines);

unset($lines[0]);
unset($lines[1]); // we do not need these lines.

foreach($lines as $line) 
{
    $var = explode(':', $line, 2);
    $arr[$var[0]] = $var[1];
}

print_r($arr);
like image 135
Ivanka Todorova Avatar answered May 23 '26 12:05

Ivanka Todorova


I don't know how you want to use those values later on. You can load data into an associative array, where the descriptions are keys:

// iterate through array
foreach($lines as $row) {
    // check if the format of this row is correct
    if(preg_match('/^([^:]*): (.*)$/', $row, $matches)) {
        // get matched data - key and value
        $data[$matches[1]] = $matches[2];
    }
}
var_dump($data);

Please note that this code allows you to fetch values with colons.

If you are not sure if the descriptions are unique you can store values as an array:

// iterate through array
foreach($lines as $row) {
    // check if the format of this row is correct
    if(preg_match('/^([^:]*): (.*)$/', $row, $matches)) {
        // get matched data - key and value
        $data[$matches[1]][] = $matches[2];
    }
}
var_dump($data);

This prevents from overwriting data parsed earlier.

like image 37
Marcin Krawiec Avatar answered May 23 '26 13:05

Marcin Krawiec