0

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? :)

Matt Raven
  • 31
  • 2
  • 4
  • You should try reading http://php.net/manual/en/function.file-put-contents.php once more. Also this might help you: http://stackoverflow.com/questions/8336858/how-to-combine-two-strings-together – Ms. Nobody Jul 16 '14 at 12:27

3 Answers3

3

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

Steve
  • 20,703
  • 5
  • 41
  • 67
1

To print multiple variables in file,

$result = array($var1, $var2);
file_put_contents('filepath', print_r($result, true));

where $var1 & $var2 variables could be of any datatype.

Rahul Rahatal
  • 648
  • 5
  • 19
0

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)."\n",FILE_APPEND | LOCK_EX);
?>

You can create array and implode it using any separator you want and concatenate implode result with new line \n.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291