PDA

View Full Version : Is this possible in php?


kobescoresagain
08 May 2006, 04:40
I have a txt file that I need to edit using php. I understand how to open it and everything. I am just having problems adding text into the file. Basically here is what the actually file would generally look like.

Some random xml tags

<item>
</item>
<item>
</item>
<item>
</item>
<item>
</item>

two closing xml tags.

The tags at the beginning will change often, so I am not 100% sure what will be there. But it will not ever need to be edited through this code (all done manually).

I basically want to add items into this code. I want to add the items to the beginning on the item list, and after the beinning random xml tags. It would result in

Some random xml tags

<new item>
</new item>
<item>
</item>
<item>
</item>
<item>
</item>
<item>
</item>

two closing xml tags.

I have been told that I need to bring the data in 1 line at a time, but I am not 100% sure what exactly I need to do. Anyh guidance would be greatly appreciated.

Rimer dal
08 May 2006, 18:00
This is untested but it is the concept... I think it is was what you wanted.
<?php

function add_data($StringToAdd){
$filename = 'test.txt';

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

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

$contents = fread($handle, filesize($filename));
if(stripos("<item>")){
$chunk1 = substr($contents,0,stripos("<item>"));
$chunk2 = substr($contents,stripos("<item>"));
$contents = $chunk1.$StringToAdd.$chunk2;
}else{
echo "Did not find <item>";
exit;
}

if (fwrite($handle, $contents) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}

echo "Success, wrote ($contents) to file ($filename)";

fclose($handle);

} else {
echo "The file $filename is not writable";
}
?>