user2519032
user2519032

Reputation: 829

Get specific data from txt file

I have txt file and I need to echo specific data in a loop.

Let's say my txt file name is this: myfile.txt

and the structure inside is like this:

etc="Orange" src="stack1"
etc="Blue" src="stack2"
etc="Green" src="stack3"
etc="Red" src="stack4"

How can I echo in PHP these values: Orange, Blue, Green, Red?

Upvotes: 0

Views: 416

Answers (3)

deon cagadoes
deon cagadoes

Reputation: 602

I exaplain all on code //comments.


<?php

$fichero = file_get_contents('./myfile.txt', false);

if($fichero === false){ //if file_get_contents() return false, the file isn't found, if its found, return data.
    echo "Can't find file.\n";
}else{ //If file is find, this condition is executed.
    $output = array(); //this variable is who will get the output of regular expression pattern from next line function.
    preg_match_all('/([A-Z])\w+/',$fichero, $output);
    for($i = 0; $i < count($output[0]); $i++){ //Iterate throught the first array inside of array of $output, count(array) is for get length of array.

        echo $output[0][$i]; //Print values from array $output[0][$i]
        if($i + 1 != count($output[0])){ //if not equal to length of array, add , at end of printed value of output[0][$i]
            echo ', ';
        }else{ //if equal to length of array, add . at end of printed value of $output[0][$i]
            echo '.';
        }

    }
}

?>

Upvotes: 0

DonCallisto
DonCallisto

Reputation: 29912

$content = file_get_content("/path/to/myfile.txt", "r");
if (false === $content) {
  // handle error if file can't be open or find
}

preg_match_all('/etc="(.*?)"/', $content, $matches);

echo implode($matches[1], ',');

With file_get_content you retrieve what's int he file.
After that you need to check if file_get_content has returned an error code (false in this case).
preg_match_all will use RegExp to filter out only what you need. In particular:

/ #is a delimiter needed 
etc=" #will match literally the letters etc="  
(.*?) #is a capturing group needed to collect all the values inside the "" part of etc value. So, capturing group is done with (). .* will match every character and ? make the quantifier "non greedy".
/ #is the ending delimiter

All matches are collected inside $matches array (is not necessary that $matches is previously defined.

Finally, you need to transform the collected values into a string and you can do this with implode function.

Upvotes: 1

treyBake
treyBake

Reputation: 6560

you can use preg_match_all for this:

<?php
    # get your text
    $txt = file_get_contents('your_text_file.txt');

    # match against etc="" (gets val inside the quotes)
    preg_match_all('/etc="([^"]+)"/', $txt, $matches);

    # actual values = $matches[1]
    $values = $matches[1];

    echo '<pre>'. print_r($values, 1) .'</pre>';

Upvotes: 1

Related Questions