Search code examples
phpfilefwritefread

Get string entry from textfile in php


I have a question. How can i get a string from a entry in a textfile.

The texfile looks like:

Blabla2|123456
Blablablabla4|475387638
Blab1|387549900

Now i want to get from Blablablabla4 the number behind the |

Whats the read file function for it?


Solution

  • You can create a custom function, if you need that value often with different keys.

    function getValueFromFile($file, $key){
        if (($handle = fopen($file, "r")) !== FALSE) {
          while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
            if($data[0] == $key){
                fclose($handle);
                return $data[1];
            }
          }
          fclose($handle);
        }
        return false;
    }
    

    and simply call it like:

    echo getValueFromFile("your file name", "Blablablabla4");