$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);
您解析文本文件,將其放入變量,然後不做任何事情。嘗試轉儲$ num。 –
你沒有返回任何東西(或使用提取的變量)。 – Vyktor