Page 1 of 1

Deleting a specified number of characters from text file

Posted: Fri Jun 03, 2005 10:16 pm
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);
?>

Posted: Sat Jun 04, 2005 3:24 am
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");

thanks

Posted: Sun Jun 05, 2005 4:08 am
by bb
Thanks a lot I played with your idea and got it to do exactly what I was looking for. Thanks.