2

I want to write the content of a string variable say $data

in to a file named data.xml the folder location will vary depends upon the content of $appId variable

like i want to write file in

  files_dir/$appId/data.xml

moreover if that file already exists than i want to rewrite otherwise i want to create the folder and then create the file data.xml

Can u suggest some way to do so.

Abhi
  • 5,501
  • 17
  • 78
  • 133
  • 3
    [google: PHP Writing String Data to a file](http://www.google.com/search?q=PHP+Writing+String+Data+to+a+file) – Your Common Sense Apr 11 '11 at 06:31
  • possible duplicate of **[4,000-ish other questions](http://stackoverflow.com/search?q=%5Bphp%5D+%2Bfile+%2Bwrite)** ... well, give or take. – Charles Apr 11 '11 at 06:32
  • 1
    possible duplicate of [How to write into a file in PHP?](http://stackoverflow.com/questions/1768894/how-to-write-into-a-file-in-php) – JohnP Apr 11 '11 at 06:35
  • Geez there are at least 5 different ways to do this in PHP, do some Google searching or something? – Christian Apr 11 '11 at 06:40

2 Answers2

5

Open file with write mode "w". will attempt to create file if does not exists otherwise truncate the file to zero length.

$handle = fopen("files_dir/$appId/data.xml", "w");

Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

You could check if the directory exists

if (!is_dir("files_dir/$appId")) mkdir("files_dir/$appId",0777);
$handle = fopen("files_dir/$appId/data.xml", "w");

Give the full path of directory and files.

designosis
  • 5,182
  • 1
  • 38
  • 57
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
0

You can use file_put_contents() to write to the file : http://php.net/manual/en/function.file-get-contents.php

And you can use mkdir() to create the folder portion : http://php.net/manual/en/function.mkdir.php

JohnP
  • 49,507
  • 13
  • 108
  • 140