Wednesday, June 4, 2008

Update content in a text file in PHP

Well its very straight forward to write content to a text file . But update a text fie is bit tricky. To update any thing you need to have a index. in text file you can use some part of the content as the index or reference. In this example the file content is image caption. its store caption for each image a gallery. and this script shows how to update those caption. Here the index or reference to update is caption. image name and caption separate by "|" symbol .

In this script file read and convert the content to array and create the updated string and write the whole thing back to the file.


$image_name="aa.jpg";
$filename="caption.txt";

//content put in to a array line by line
$lines = file($filename);
//seperate the caption and image name
foreach($lines as $l)
{
list($imgname, $captext) = explode("|", $l);
// crate associate array.index is image name, content is caption
$cap_array[$imgname] = $captext;
}
//update the new caption for the given image in the array
$cap_array[$image_name]=$cap;
// create the updated srting
foreach($cap_array as $key=>$val)
{

$str.=$key."|".$val;

}

unlink($filename);

if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// Write the string back to the file
if (fputs($handle, $str) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}


?>

No comments: