Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 732
Morne Zeelie Avatar asked Jun 27 '11 12:06

Morne Zeelie


2 Answers

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.

like image 112
Marc B Avatar answered Nov 03 '22 03:11

Marc B


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

like image 42
Alex Avatar answered Nov 03 '22 04:11

Alex