2
\$\begingroup\$

I have the following code, which gets the data from 3 text files and puts them into 3 variables. How can I refactor this to make it smaller?

$handle = fopen($template_filename, "r");
if (filesize($template_filename) > 0)
{
 $email_template = fread($handle, filesize($template_filename));
}
fclose($handle);
// get the subject from a text file
$handle = fopen($subject_filename, "r");
if (filesize($subject_filename) > 0)
{
 $subject_template = fread($handle, filesize($subject_filename));
}
fclose($handle);
// get the footer from a text file
$handle = fopen($footer_filename, "r");
if (filesize($footer_filename) > 0)
{
 $footer_template = fread($handle, filesize($footer_filename));
}
fclose($handle);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 10, 2011 at 16:06
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

For one thing, you can use file_get_contents:

$email_template = file_get_contents($template_filename);
$subject_template = file_get_contents($subject_filename);
$footer_template = file_get_contents($footer_filename);
answered Oct 10, 2011 at 19:31
\$\endgroup\$
1
\$\begingroup\$

Encapsulate the repetitive parts in a function openFile(), open files with file_get_contents, and finally, check for empty file size via strlen in the ternary and return the contents or an error ("Empty file." in this case - would suggest you replace with an error function call or something).

function openFile($filename){
 $contents = file_get_contents($filename);
 return strlen($contents) > 0 ? $contents : "Empty file.";
}
$email_template = openFile($email_filename);
$subject_template = openFile($subject_filename);
$footer_template = openFile($footer_filename);
# Test case
echo openFile("http://www.google.com");
answered Jul 16, 2012 at 19:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.