Deleting a specified number of characters from text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bb
Forum Newbie
Posts: 8
Joined: Fri Jun 03, 2005 10:03 pm

Deleting a specified number of characters from text file

Post by bb »

I wrote a little program that writes XML to a file.

My problem is when I go to append more information PHP writes to the very end of the file, below the closing XML parent tag making it invalid. So I am pursuing one of two possible solutions.

1. PHP deletes the parent tag which is on the last line of the file and is 9 characters long.

2. PHP writes between the last xml tag and the closing parent tag.

I'm thinking deleting the last line would be the easiest, but I'm not too sure.

Any help or insight anyone could give me would be awesome.

My script so far is just this simple append script that writes xml:

Code: Select all

<?php
$category = $_GET["category"];
$toplink = $_GET["toplink"];
$program = $_GET["program"];
$description = $_GET["description"];
$funder = $_GET["funder"];
$due = $_GET["due"];
if (strlen($_GET['nofa']) > 0) {
	$nofa = "<nofa value=\"{$_GET['nofa']}\">NOFA</nofa>";
} else {
	$nofa .= "<nofa value=\"\"></nofa>";
}
$application = $_GET["application"];
$guide = $_GET["guide"];
print("<p>The opportunity has been <a href=\"fundopsxml.xml\">added</a></p><p><a href=\"fundreportadmin.php\">Add Another</a></p><a href=\"fundreport.php\">Build All Reports and Feeds</a>");
$out = fopen("fundopsxml.xml", "a");
if (!$out) {
print("Could not append to file");
exit;
}
fputs ($out,implode,("\n"));
fwrite($out,"\n<opportunity>\n	<category>$category</category>\n	<toplink>$toplink</toplink>\n	<program>$program</program>\n	<description>$description</description>\n	<funder>$funder</funder>\n	<duedate>$due</duedate>\n	$nofa\n	<application>$application</application>\n	<guide>$guide</guide>\n</opportunity>\n");
fclose($out);
?>
User avatar
wwwapu
Forum Contributor
Posts: 197
Joined: Wed Apr 07, 2004 11:57 am
Location: Turku, Finland

Post by wwwapu »

I suppose your 9 characters long parent tag is unique? if so you can do something like:

Code: Select all

$old_data=file_get_contentens("your_xml_file");
$end_tag="123456789";
$new_data="data_composed_from_$_GET".$end_tag;
$data_to_be_written=str_replace($end_tag, $new_data, $old_data);
write_to_file($data_to_be_written, "your_xml_file");
bb
Forum Newbie
Posts: 8
Joined: Fri Jun 03, 2005 10:03 pm

thanks

Post by bb »

Thanks a lot I played with your idea and got it to do exactly what I was looking for. Thanks.
Post Reply