Search code examples
phpfilefile-get-contentsfile-read

PHP read a file and store the informations in variables


Is there any way to read a text file and store the information to variables?

My file.txt is like,

Timestamp 1343872162
No.of tall 2
No.of long 5
tall1 171
tall2 172
long1 170
long2 168
long3 168
long4 166
long5 166

That is, I have to retrieve these values from that file as $time=1343872162, $tall1=171, $tall2=172,$long1=170 etc. Any thoughts?

Thanks!


Solution

  • Try this:

    <?php
    $handle = @fopen("/tmp/inputfile.txt", "r");
    if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            list( $key, $value ) = explode( ' ', trim($buffer) );
            $$key = $value; //Double $$ to set a var with the string name in $key
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    ?>