Search code examples
phparraysfopenexplodefgets

PHP explode a txt file


I have the following txt file:

++Marry++M++B++NY++

++Jack++F++O++LS++

write to a .txt file:

Name:Marry

Sex:M

Blood type:B

City:NY

Name:Jack

Sex:F

Blood type:O

City:LS

My code is:

$fn = fopen("test.txt","r") or die("fail to open file");
 
$content = array();
 
 while($row = fgets($fn)) {

    $num = explode("++", $row);
    $name = $num[0];
    $sex = $num[1];
    $blood =  $num[2];
    $city = $num[3];
 }

$fp = fopen('output.txt', 'w');     
fwrite($fp, $row);
fclose($fp);

Should this work? Because it returns nothing.

Thx.


Solution

  • $fn = fopen("test.txt","r") or die("fail to open file");
    
    while($row = fgets($fn)) {
      list( $sName, $sSex, $sBlood, $sCity ) = explode( "++", $row );
    
      echo 'Name:' . $sName . '<br />';
      echo 'Sex:' . $sSex . '<br />';
      echo 'Blood type:' . $sBlood . '<br />';
      echo 'City:' . $sCity . '<br />';
    }
    
    fclose( $fn );
    

    To write to a file you must fist create a buffer and then write to the file. The easiest way to do this would be with file_put_contents. Be aware of that the file_put_content method uses more memory then fopen, fwrite and fclose does.

    $fn = fopen("test.txt","r") or die("fail to open file");
    
    $sBuffer = '';
    while($row = fgets($fn)) {
        list( $sName, $sSex, $sBlood, $sCity ) = explode( "++", $row );
    
        $sBuffer .= 'Name:' . $sName . PHP_EOL;
        $sBuffer .= 'Sex:' . $sSex . PHP_EOL;
        $sBuffer .= 'Blood type:' . $sBlood . PHP_EOL;
        $sBuffer .= 'City:' . $sCity . PHP_EOL;
    
        $sBuffer .= PHP_EOL; // There will be a empty line after each "set"
    }
    
    fclose( $fn );
    
    file_put_contents( 'path/to/file.txt', $sBuffer );
    

    With fopen, fwrite and fopen.

    $fn = fopen("test.txt","r") or die("fail to open file");
    
    $rWrite = fopen( 'path/to/file.txt', 'w' ) or die( 'Could not open file for writing' );
    
    while($row = fgets($fn)) {
        list( $sName, $sSex, $sBlood, $sCity ) = explode( "++", $row );
    
        fwrite( $rWrite, 'Name:' . $sName . PHP_EOL );
        fwrite( $rWrite, 'Sex:' . $sSex . PHP_EOL );
        fwrite( $rWrite, 'Blood type:' . $sBlood . PHP_EOL );
        fwrite( $rWrite, 'City:' . $sCity . PHP_EOL );
    
        fwrite( $rWrite, PHP_EOL ); // There will be a empty line after each "set"
    }
    
    fclose( $fn );
    fclose( $rWrite );