I'm trying to figure out how to write multiple variables to file using file_put_content.
My code:
<?php
$file = 'file.txt';
$data1 = "John Smith";
file_put_contents($file, $data1, FILE_APPEND | LOCK_EX);
?>
I have additional variables such as $data2, $data3 and $data4. I tried:
<?php
$file = 'file.txt';
$data1 = "John Smith";
$data2 = "Street Address";
$data3 = "Plumber";
$data3 = "Phone nuber";
file_put_contents($file, $data1, $data2, $data3, $data4,FILE_APPEND | LOCK_EX);
?>
but it's not working. I need to write all variables to file.txt so it looks like this:
John Smith Stret Address Plumber Phone Number
and each time when the script has been launched it should add new variables in a new line e.g:
John Smith Stret Address Plumber Phone Number
Mike Johnson Stret Address lectrician Phone Number
etc etc. Any ideas? :)
I would do it this way:
<?php
$file = 'file.txt';
$data1 = "John Smith";
$data2 = "Street Address";
$data3 = "Plumber";
$data3 = "Phone nuber";
$data = array($data1, $data2, $data3, $data4);
file_put_contents($file, implode(' ',$data)."
",FILE_APPEND | LOCK_EX);
?>
You can create array and implode it using any separator you want and concatenate implode result with new line .
Use string concatenation
$file = 'file.txt';
$data = "John Smith ";
$data .= "Street Address ";
$data .= "Plumber ";
$data .= "Phone nuber";
file_put_contents($file, $data,FILE_APPEND | LOCK_EX);
or directly in the function call:
file_put_contents($file, $data1 . $data2 . $data3 . $data4, FILE_APPEND | LOCK_EX);
*note added space chars to values to get desired formatting