Friday, April 24, 2009

How to read html content in PHP and append the text

In php we have code for reading a file. But in some scenarios we may need to rad the html and in the html file we need to append certain variables with the external variables.

For example:
We need to send an email in a particular website. We will design the mail format in the html and save it. In the html file we will declare the dynamic variables with the special characters(like #username#). These are the dynamic variables which will change, depends on the user side functionality.

This is the sample code for obtaining the above task.

$txtsubject="Your new password";
$g_phpMailer_method = 2; // You will define the your mailer method
$g_smtp_host = 'XX.XX.XXX.XXX'; // you will define the host name
$g_smtp_username = 'XXXXX'; // Your SMTP admin name
$g_smtp_password = 'XXXXX'; // Your SMTP admin password
$to="testmail@gmail.com"; // To email address
$email="testmail@gmail.com"; // From email address
$subject="Your test subject";
$myFile = "tempfolder/mailformat.html";
$fh = fopen($myFile, 'r');
$body = fread ($fh, filesize($myFile));
$body= str_replace( '#mysubject#', $subject , $body);
$body = str_replace( '#myemail#', $email , $body);
$from="from email address";
$headers = 'MIME-Version: 1.0' . "\r\n".'Content-type: text/html; charset=iso-8859-1' . "\r\n".
'From:'.$from."\r\n" .'X-Mailer: PHP/' . phpversion();
if(mail($to, $txtsubject, $body, $headers))
{
echo "Mail sent";
}

Here we use fopen to open the html file and fread to read the html content into some variable. str_replace method is used to replace the ## between variables with the dynamic variables.

0 comments:

Post a Comment