Page 1 of 1
can I read a multiline variable like a multiline file?
Posted: Wed Nov 11, 2009 11:46 pm
by paul_g
I have a routine that calls a function which returns a multiline string. (a tab delimited text db, essentially).
I'm wondering if there is a way to read that variable line by line in a foreach loop as if it were a file, without first writing it to disk and calling the file() function and without turning it first into a huge array.
Thanks for any tips and hints
Paul
Re: can I read a multiline variable like a multiline file?
Posted: Wed Nov 11, 2009 11:50 pm
by John Cartwright
You could explode() on newlines (or whatever line delimeter) which returns an array
Code: Select all
$csvdatalines = explode(PHP_EOL, $csvdata); //split on newlines
foreach ($csvdatalines as $row) {
// process
}
Re: can I read a multiline variable like a multiline file?
Posted: Thu Nov 12, 2009 2:28 am
by paul_g
John Cartwright wrote:You could explode() on newlines (or whatever line delimeter) which returns an array
Code: Select all
$csvdatalines = explode(PHP_EOL, $csvdata); //split on newlines
foreach ($csvdatalines as $row) {
// process
}
Thanks John.
Is that feasible with a 12000+ item array?
I was worrying that such a large array would be a strain on resources.
...
Re: can I read a multiline variable like a multiline file?
Posted: Thu Nov 12, 2009 4:07 am
by requinix
If you're concerned about that an alternative is to use
strtok. Rather than deal with an array you'll deal with one string after another.
Code: Select all
$lines = explode("\n", $string);
foreach ($lines as $l) {
}
// versus
for ($l = strtok($string, "\n"); $l; $l = strtok("\n")) {
}
Re: can I read a multiline variable like a multiline file?
Posted: Thu Nov 12, 2009 4:14 am
by Apollo
paul_g wrote:Is that feasible with a 12000+ item array?
I was worrying that such a large array would be a strain on resources.
The array won't need that much more memory than the original single string. So unless you have LOTS of columns per line or very long values, 12000 rows should be rather insignificant for any decent webserver.
Re: can I read a multiline variable like a multiline file?
Posted: Thu Nov 12, 2009 2:43 pm
by paul_g
Thanks. You guys rock.
You've taught me some new tricks!