Issue
i am creating a new CSV file from the user input in php like this:
public function handle()
{
$a = readline('Enter a string: ');
$list = array (
array($a)
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
echo PHP_EOL . "CSV created!";
}
and getting the output like this:
but i want the output to be like this:
h,e,l,l,o, ,w,o,r,l,d
each character in different column
how can i archive this?
Solution
You can split a string into chunks—in this case, every chunk will be 1 character long—with str_split
.
$a = readline('Enter a string: ');
$list = array (
str_split($a)
);
If later you want to add some more columns, then you can do:
$a = readline('Enter a string: ');
$list = array (
array_merge(array("foo", "bar"), str_split($a))
);
Edit:
In your question you ask for "every character in a different column", but from your comment I take it you want one column but the characters split by spaces? In that case:
$a = readline('Enter a string: ');
$list = array (
implode(',', str_split($a))
);
fputscsv
will make sure that the string is escaped properly.
If you want both multiple columns and every column ending in a space, then split the string as normal but also modify every array entry by adding a space at the end:
$a = readline('Enter a string: ');
$list = array (
array_map(
function($char) { return "$char,"; },
str_split($a)
)
);
array_map
will run a function ("callable") for every array entry.
Answered By - RickN Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.