Help with writing to a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
davisaggie
Forum Newbie
Posts: 16
Joined: Mon Aug 20, 2007 3:40 pm
Location: Salinas, CA

Help with writing to a file

Post by davisaggie »

I need some help with writing to a file. I have a script that generates another script based on the contents of a directory. Here is the current script I am running
file_array_gen.php:

Code: Select all

<?php

if(($dhandle = opendir('C:\\grower')) !== false) { 
	$file_array= array();
	while(($file=readdir($dhandle))!== false){
			if($file !== '.' && $file !== '..'){
				$file_array[] = $file;}
	}
	shuffle($file_array);
	$file_out = '<?php \r\n \$file_array = array(); \r\n';
	for($i=0; $i <= count($file_array) - 1; $i++){
        $file_exp = explode('.', $file_array[$i]);
	    $ext = array_pop($file_exp);
		if($ext == 'pdf'){
			$file_out .= '\$file_array[] = "'.$file_array[$i].'";\r\n';
		}
	}	
	$file_out .= '\r\n ?>';
	if(($fhandle = file_put_contents('C:\\xampp\\htdocs\\file_array.php', $file_out)) == false) {
	die('Unable to open file.'); exit;}
	closedir($dhandle);
} else { die('Unable to open directory.'); exit;}

exit;

?>
The file it generates, file_array.php currently looks like this:

Code: Select all

<?php \r\n \$file_array = array(); \r\n\$file_array[] = "measures_expansion.pdf";\r\n\$file_array[] = "Measures_Formula.pdf";\r\n\$file_array[] = "measures.pdf";\r\n\$file_array[] = "Measures_Doc.pdf";\r\n\r\n ?>
When I try to use file_array.php in an include statement I am getting errors about unrecognized characters. Do I need to include the '\r\n' or the '\' before the '$'?

*EDIT*
Also is there a way to output to the file so each $file_array[] statement is on a new line to ease readability?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

Use double quotes instead of single.
There are 10 types of people in this world, those who understand binary and those who don't
davisaggie
Forum Newbie
Posts: 16
Joined: Mon Aug 20, 2007 3:40 pm
Location: Salinas, CA

*SOLVED* Help with writing to a file

Post by davisaggie »

Vlad,
Thank you so much! that did the trick.
Post Reply