DragonSlayer
DragonSlayer

Reputation: 837

PHP when writing to file, How to prepend and append text to a file with existing text?

I'm creating a xml file with PHP here is some sample code.

 $myFile = "example_file.xml";
    $fh = fopen($myFile, 'w');
  while($row = mysql_fetch_array($result))
  {

  $stringData = "<field name=\"id\">$page_id</field>
                              <field name=\"url\">http://myfundi.co.za/a/$page_url</field>
                              <field name=\"title\">$pagetitle</field>
                              <field name=\"content\">$bodytext</field>
                              <field name=\"site\">Myfundi</field>";
                          fwrite($fh, $stringData);
    }             

    fclose($fh);

What I need to do is when the first content is written to the text file, I need to prepend and append some more text.

I need to prepend and append to the data that already exists.

How can I do that?

Thanks

Upvotes: 5

Views: 5824

Answers (3)

Alex
Alex

Reputation: 365

You can't prepend to a file. Read out the content, prepend your new text and write it to your file. If you want so append something, you just open the file with flag 'a' and write in it. See http://php.net/manual/de/function.fopen.php

Upvotes: 1

Try this:

http://php.net/manual/en/function.fwrite.php

Hope this helps.

Upvotes: -1

Marc B
Marc B

Reputation: 360872

You can't "prepend" text to a file directly. The only practical method is to open a new temporary file, write out the new text, and then copy the original text onto the end.

Upvotes: 5

Related Questions