Search code examples
phpfilefileoutputstream

i want to store readed file output in variable


in PHP I want each string read by "fgets()" function in a separate variable. Below is my code

$handle = @fopen("txtfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

An output of this code is:

I am Demo

I want this output as:

$word1 = I
$word2 = am
$word3 = Demo

Solution

  • <?php
    
    $handle = @fopen("txtfile.txt", "r");
    $text = '';
    if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            $text .= $buffer;
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    
    $array = explode(' ', $text);
    
    $i = 1;
    
    foreach ($array as $word) {
        ${"word$i"} = $word;
        $i++;
    }
    

    Now you have each word saved in a different var