Saturday, February 21, 2009

PHP: how to delete the last line of a file?

i'm a little friend of MySQL, but a big friend of writing content to files, text files or csv (comma-separated-value) files. one reason is that i haven't really worked that much with MySQL. i just know the basics and have usually worked with them when setting up a forum or webshop. those scripts are readily available all across the internet.

i was going to set up a table using either XML or PHP's array function with a script that would write either the XML file, or a PHP fie that i could include in another script which in turn could be used to create an XML file or simply HTML.

i looked at various examples and tutorials on the internet on how to manipulate XML files with PHP, but i wasn't too happy about where the new elements would be placed in the XML document eventually.

of course one of the problems would always be: how would i squeeze a new set of elements before the closing root element; or how would i get rid of the ?> at the end of the php file i wish to include somewhere else.

the basic idea i found here: http://bytes.com/groups/php/11847-how-delete-last-line-file.

below is the code snippet from that page that got me going:

$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($i=0;$i<count($inp)-1;$i++)
fwrite($out,$inp[$i]);
fclose($out);


in this particular case the information of one file is written to another file. (not 100% what i was looking for).

in the end i started using this example:

$my_input = '$my_'.$_GET['my_number'].' = array ( $my_date => \''.$_GET['my_date'].'\', $my_city => \''.$_GET['my_city'].'\', $my_links => \''.$_GET['my_links'].'\', \'$my_update => \''.$_GET['my_update'].'\', );'."\n";
// load the data and delete the line from the array
$lines = file('#_MyIncludeFile.inc.php');
$last = sizeof($lines)-1;
unset($lines[$last]);

// write the new data to the file
$input = fopen('#_MyIncludeFile.inc.php','w');
fwrite($input, implode('', $lines));
fwrite($input, $my_input);
fwrite($input, "?>");
fclose($input);


the $_GET variables are submitted from a form:
<form method="GET" action="WriteToFile.php">
<table>
<tr><td>my my number:</td><td><input type="text" name="my_number" /></td></tr>
<tr><td>my my date:</td><td><input type="text" name="my_date" /></td></tr>
<tr><td>my my city:</td><td><input type="text" name="my_city" /></td></tr>
<tr><td>my my links:</td><td><input type="text" name="my_links" /></td></tr>
<tr><td><input type="hidden" name="my_update" value="<?=time();?>" /><br />
<br /><input type="submit" value="send" /></td></tr>
</table>
</form>


the WriteToFile.php file also contains this form for further input.

this script writes CSV data to a PHP file which can then be used elsewhere for further analyzes.

i think that says it all ... or are there any questions?

Good Luck again!

tom.paine


No comments: