Reputation: 1225
I have encountered a problem that I need to solve using PHP.
I have a multiline input that looks like this:
a,b,c,d
a=10 tools
b=50 subtools
c=80 othertools
I want to read input using stdin but I'm only able to read the first line.
using fscanf(STDIN, "%s\n", $name);
How do I read the multiple input lines and save them to a list? I want to use a comma as separator for first-line and space as a separator for the rest.
Upvotes: 2
Views: 1889
Reputation: 13047
There is many built-in way, but the shortest and strongest way to handle all cases, huge stream length, multi-lines or not, is stream_get_contents()
var_dump(stream_get_contents(STDIN));
exit;
Upvotes: 0
Reputation: 94642
Using fgets
you can do
$c = 0;
do {
$f = fgets(STDIN);
echo "line: $f";
if ( $c == 0) {
echo 'its a a,b,c,d type line' . PHP_EOL;
} else {
echo 'its a a=10 tools' . PHP_EOL;
}
$c++;
} while ($c < 5);
echo 'END';
Or
$c = 0;
while ($f = fgets(STDIN) !== FALSE and $c<4) {
echo "line: $f";
if ( $c == 0) {
echo 'its a a,b,c,d type line' . PHP_EOL;
} else {
echo 'its a a=10 tools' . PHP_EOL;
}
$c++;
}
echo 'END';
Upvotes: 2