3

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 ":"?

3
  • 1
    Something like ready line by line and then remove all the chars before the ":"? Commented Jun 30, 2013 at 15:31
  • You could easily use the regex from my earlier answer. Commented Jun 30, 2013 at 15:33
  • use JSON. json_encode and json_decode instead of writing your own parser. Other options are serialize and XML Commented Jun 30, 2013 at 15:33

4 Answers 4

9

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);
Sign up to request clarification or add additional context in comments.

3 Comments

You can also trim like this: $arr[$var[0]] = trim($var[1]);
@AurelioDeRosa this is a good advice. Now he can do whatever he wants. $var[0] is the "Description1", "Descrption2" (etc...) and $var[1] holds the value. :)
Use the limit argument of explode ($var = explode(':', $line, 2);)
1

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.

Comments

0

Since $lines is an array, you should loop it looking for the ":" and separating the line in two: description and value.

Then:

<?php
$variables = array();
unset($lines[0]); //Description line
unset($lines[1]); //-------

foreach ($lines as $line) {
    $tempArray = explode( ": ", $line ); //Note the space after the ":", because
                                           values are stored with this format.
    $variables[$tempArray[0]] = $tempArray[1];
}
?>

There you have in variables an array, whose keys are the descriptions and values are your values.

Comments

0

You could use a regular expression to split the line and retrieve the parte after ":" or just yse the explodecommand which returns an array of the string split by every ":" such as:

foreach ($lines as $line_num => $line) {
    $split_line = explode(":", $line);
    // echo the sencond part of thr string after the first ":"
    echo($split_line[1])
    // also remove spaces arounfd your string
    echo(trim($split_line[1]));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.