Reading and Writing Comma-Separated Data
<?php
$commafile = "data.txt";
if (file_exists ($commafile)){
$rows = file ($commafile);
for ($i = 0; $i < count ($rows); $i++){
$exprow = explode (",", $rows[$i]);
echo "ID: " . $exprow[0] . "<br />";
echo "Name: " . $exprow[1] . "<br />";
echo "Author: " . $exprow[2] . "<br />";
echo "<hr />";
}
} else {
echo "File does not exist.";
}
$idarray = array ("1","2","3");
$namearray = array ("Book 1","Book 2","Book 3");
$authorarray = array ("Author","Author","Author");
$newfile = "data.txt";
try {
if ($readfile = fopen ($newfile, "w")){
for ($i = 0; $i < count ($idarray); $i++){
$writestring = $idarray[$i] . "," . $namearray[$i] . "," . $authorarray[$i] . "\n";
fwrite ($readfile, $writestring);
}
fclose ($readfile);
} else {
throw new exception ("Sorry, the file could not be opened.");
}
} catch (exception $e) {
echo $e->getmessage();
}
?>
Related examples in the same category