$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 );
要写入文件,您必须先创建一个缓冲区,然后再写入文件。最简单的方法是使用 file_put_contents。请注意,file_put_content 方法比 fopen、fwrite 和 fclose 使用更多内存。
$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 );
使用 fopen、fwrite 和 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 );