DZone 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

Michael has posted 27 posts at DZone. View Full User Profile

PHP To Generate HTML File

01.18.2006
| 1297 views |
  • submit to reddit
        // The following code snippets are examples of using a form to generate an html file.



<html>
<head>
<title>Test</title>
<!-- Form.html File -->

<SCRIPT LANGUAGE="JavaScript">

	
function ignoreSpaces(string) 
	{
		var temp = "";
		string = '' + string;
		splitstring = string.split(" ");
		for(i = 0; i < splitstring.length; i++)
		temp += splitstring[i];
		return temp;
	}

</script>

</head>
<body>
<form name="subscribe" action="post.php" method="post">
First Name : <input type="text" name="fname" onBlur="this.value=ignoreSpaces(this.value);" /><br />
Last Name : <input type="text" name="lname" onBlur="this.value=ignoreSpaces(this.value);" /><br />
Text : <textarea name="htmlArea" rows=10 cols=50 wrap="off"></textarea>
<br />
<input type="submit" name="submit" value="Post" />
</form>
</body>
</html> 

<?php
// Post.php File

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$text = $_POST['htmlArea'];

if(!$fname) // If email address is not entered show error message
{
    echo "Please enter your first name.";
    exit;
}
else
if(!$lname) // If email address is not entered show error message
{
    echo "Please enter your last name.";
    exit;
}
else
if(!$text) // If email address is not entered show error message
{
    echo "Please enter text.";
    exit;
}
else
{
    
    
    $fullname = $fname . $lname;
    $filename = $fullname . ".html"; // File which holds all data
    
    
    $content = nl2br("$text");
    $fp = fopen($filename, "w"); // Open the data file, file points at the end of file 
    $fw = fwrite( $fp, $content ); // Write the content on the file
		fclose($fp);
			
			
   /*
   // Used to check if file already exists
    if (file_exists($filename)) {
    	echo "The file $filename exists.  ";
    }
    else
    {
    	 $content = nl2br("$text");
    //$content = "$text\n"; // Content to write in the data file
    $fp = fopen($filename, "w"); // Open the data file, file points at the end of file 
    $fw = fwrite( $fp, $content ); // Write the content on the file
			fclose($fp);
    }
    */
   
    
    if(!$fw) echo "Couldn't write the entry.";
    else echo "Successfully wrote to the file <a href=" . $fullname . ".html>" . $fullname . ".html</a>";
}


?>