Reputation: 308
I"m trying to make a web form that outputs to flat text file line by line what the input to the web form is. Several of the fields are not required but the output file must input blank spaces in for whatever is not filled out. Here is what I'm trying:
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = str_pad($output, 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = str_pad($output, 6);
}
write_line($output);
function write_line($line){
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
However, when I check my output the spaces don't show up. Any ideas on what's going on with this? Thanks in advance!
Upvotes: 2
Views: 1679
Reputation: 1137
str_pad() won't add that number of spaces, but rather makes the string that length by adding the appropriate number of spaces. Try str_repeat():
$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
$output .= $_POST["trans_date"];
}else{
$output = $output . str_repeat(' ', 6);
}
if(!empty($_POST['chart'])) {
$output .= $_POST["chart"];
}else{
$output = $output . str_repeat(' ', 6);
}
write_line($output);
function write_line($line) {
$file = 'coh.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $line . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
}
Cheers!
Upvotes: 1
Reputation: 53888
str_pad
is padding with spaces, not adding spaces. You're padding an existing value with spaces so that it is 6 characters long, not adding 6 whitespaces to the value. So if $_SESSION["emp_id"]
is 6 characters long or more, nothing will be added.
Upvotes: 3