Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Some file manipulation functions in PHP (See related posts)

Here are some file manipulation functions in PHP:

   1  function fileToArray($file) {
   2  	if (!$array = file($file)) {
   3  		die("fileToArray: Could not read file!");
   4  	}
   5  	return $array;
   6  }
   7  
   8  function fileToString($file) {
   9  	if (!$string = file_get_contents($file)) {
  10  		die("fileToString: Could not read file!");
  11  	}
  12  	return $string;
  13  }
  14  
  15  function stringToFile($file, $string) {
  16  	if (!$handle = fopen($file,"w")) {
  17  		die("stringToFile: Could not open file");
  18  	}
  19  	if (!fwrite($handle, $string))
  20  		die("stringToFile: Could not write file");
  21  	}
  22  	fclose($handle); // Should the close handle be error checked, or would I be over doing it?
  23  }
  24  
  25  function arrayToFile($file, $array) {
  26  	if (!$handle = fopen($file,"w")) {
  27  		die("arrayToFile: Could not open file");
  28  	}
  29  	for ($i = 0; $i < count($array); $i++) {
  30  		if ($i == count($array) - 1) {
  31  			if (!fputs($handle, $array[$i])) {
  32  				die("arrayToFile: Could not write file");
  33  			}
  34  		} else {
  35  			if (!fputs($handle, $array[$i]."\n")) {
  36  				die("arrayToFile: Could not write file");
  37  			}
  38  		}
  39  	}
  40  	fclose($handle);
  41  }

You need to create an account or log in to post comments to this site.


Click here to browse all 5349 code snippets

Related Posts