...

View Full Version : add content to a specific position of a file



ktsixit
12-11-2008, 11:01 AM
hi, I'm creating a php script for adding content into an xml file, in a specific position. The xml file ends with a "</data>" tag, so I believe that a good way to add content before "</data>" is to use fseek.


$fname = "demo.xml";
$fhandle = fopen($fname,"r");
fseek($fhandle,-7,SEEK_END);

$content = "<title>".$_POST['title']."</title>";
$content .= "<text>".$_POST['text']."</text>";

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

The problem is that this code deletes all contents of the xml file and adds the current $content. So I suppose I don't use fseek right. What I want to do is add content before "</data>" and keep the rest of the file as it was.

xml file:

<?xml version="1.0" encode="UTF-8"?>
<!DOCTYPE data[
<!ELEMENT title(comments, image)>
<!ATTLIST title name CDATA #REQUIRED>
<!ELEMENT text (#PCDATA)>
]>
<data>
<title name="title 1">
<text>text1</text>
</title>

<title name="title 2">
<text>text2</text>
</title>

<title name="title 3">
<text>text 3</text>
</title>
<--------- add text here
</data>

mic2100
12-11-2008, 12:21 PM
hi,

try this it shud work fine on PHP5 systems




$fname = "demo.xml";
//$fhandle = fopen($fname,"r");
//fseek($fhandle,-7,SEEK_END);

$current_xml = substr(file_get_contents($fname), 0, -7);

$content = $current_xml."\n<title>".$_POST['title']."</title>";
$content .= "\n<text>".$_POST['text']."</text>";
$content .= "\n</data>";

$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

ktsixit
12-11-2008, 01:04 PM
I should know it from the start that string methods are the right choice for this :) I changed the code a little bit and finally it looks like this:


$fname = "new.xml";
$fhandle = fopen($fname,"r");
$filestring = file_get_contents($fname);

$content = "\n".'<title name="'.$_POST['title'].'">'."\n";
$content .= "<text>".$_POST['text']."</text>"."\n"."</title>"."\n\n";

$newstring = substr_replace($filestring, $content, -7, 0);

$fhandle = fopen($fname,"w");
fwrite($fhandle,$newstring);
fclose($fhandle);

Thank you very much for your help :o



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum