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
can I read a multiline variable like a multiline file?
Moderator: General Moderators
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: can I read a multiline variable like a multiline file?
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?
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?
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?
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.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.
Re: can I read a multiline variable like a multiline file?
Thanks. You guys rock.
You've taught me some new tricks!
You've taught me some new tricks!