Jump to content

Join External files


Juniorflip

Recommended Posts

Hopefully this is a simple function to do but I am looking to join 3 external file and output to a single file

example

header.txt = hello
body.txt = welcome
footer.txt = goodbye

I need a php function that will open all three text file and print the value to a new text file

example

greeting.txt = hello
                    welcome
                    goodbye

Is this possible to do?

Thanks in advance
Link to comment
https://forums.phpfreaks.com/topic/24282-join-external-files/
Share on other sites

This should work

[code]$header = get_file_contents('header.txt');
$body = get_file_contents('body.txt');
$footer = get_file_contents('footer.txt');

$greeting_fp = fopen('greeting.txt', 'w');
fwrite($greeting_fp, $header);
fwrite($greeting_fp, $body);
fwrite($greeting_fp, $footer);
fclose($greeting_fp);[/code]

It's better if you check every function call for errors, like

[code]if ($header === false) die("Couldn't read header.txt\n");[/code]
Link to comment
https://forums.phpfreaks.com/topic/24282-join-external-files/#findComment-110447
Share on other sites

So if I wanted to make a function it would go like this

[code]
Function create_greet {
$header = get_file_contents('header.txt');
$body = get_file_contents('body.txt');
$footer = get_file_contents('footer.txt');
if ($header === false) die("Couldn't read header.txt\n");
$greeting_fp = fopen('greeting.txt', 'w');
fwrite($greeting_fp, $header);
fwrite($greeting_fp, $body);
fwrite($greeting_fp, $footer);
fclose($greeting_fp);
}
create_greet();
[/code]
Link to comment
https://forums.phpfreaks.com/topic/24282-join-external-files/#findComment-110454
Share on other sites

Yes.. and for every other function too.

It may seem like a lot of work, but it saves a lot of debugging work later.

[code]Function create_greet() {
$header = get_file_contents('header.txt');
if ($header === false) die("Couldn't read header.txt\n");
$body = get_file_contents('body.txt');
if ($body === false) die("Couldn't read body.txt\n");
$footer = get_file_contents('footer.txt');
if ($footer === false) die("Couldn't read footer.txt\n");
$greeting_fp = fopen('greeting.txt', 'w');
if ($greeting_fp === false) die("Couldn't open greeting.txt\n");
fwrite($greeting_fp, $header);
fwrite($greeting_fp, $body);
fwrite($greeting_fp, $footer);
fclose($greeting_fp);
}
create_greet();[/code]

It's not so essential to check fwrite() and fclose(), since they very rarely fail.
Link to comment
https://forums.phpfreaks.com/topic/24282-join-external-files/#findComment-110458
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.