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);
\$\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);
\$\endgroup\$
0
\$\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");
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.