I just trying to understand how to use fwrite. In the below code, i am trying to save the output in the text file. I am just getting an empty txt file. Can anyone please tell me what i am doing wrong here
<?php
$name = fix_name("ALAN", "james", "LiM");
echo $name[0] . " " . $name[1] . " " . $name[2];
function fix_name($n1, $n2, $n3) {
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
return array($n1, $n2, $n3);
}
$fp = fopen("name.txt", "wb");
$written = fwrite($fp, $name);
fclose($fp);
?>
You are passing an array to fwrite.
If you enable error reporting with
error_reporting(E_ALL);
You would get a warning saying
Warning: fwrite() expects parameter 2 to be string, array given in file.php on line 16
Either return a string from your function
return $n1 . ', ' . $n2 . ', ' . $n3;
Or outside the function, use implode to get a string from the elements of the array
$name = implode(', ',fix_name("ALAN", "james", "LiM"));
Also, outside the function, print out just the $name variable
print $name;
In your text file you will have this
Alan, James, Lim
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With