can I read a multiline variable like a multiline file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
paul_g
Forum Newbie
Posts: 3
Joined: Wed Nov 11, 2009 11:38 pm

can I read a multiline variable like a multiline file?

Post 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
User avatar
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?

Post 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
}
paul_g
Forum Newbie
Posts: 3
Joined: Wed Nov 11, 2009 11:38 pm

Re: can I read a multiline variable like a multiline file?

Post 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.

...
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: can I read a multiline variable like a multiline file?

Post 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")) {
}
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: can I read a multiline variable like a multiline file?

Post 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.
paul_g
Forum Newbie
Posts: 3
Joined: Wed Nov 11, 2009 11:38 pm

Re: can I read a multiline variable like a multiline file?

Post by paul_g »

Thanks. You guys rock.

You've taught me some new tricks!
Post Reply