prudens Posted May 29, 2008 Share Posted May 29, 2008 Hey, So let's say I have a file called "schools.txt": University of Alaska University of California CalTech University of Phoenix How do I use pHp to read the file and store each line in an array Skool[]? and say I have a webpage called "groups.html" <html> <head> <title> </head> LINE 1 LINE 2 </html> How do I skip the <html> tags and get straight to LINE1 and LINE2 and read and store in array? Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted May 29, 2008 Share Posted May 29, 2008 array file ( string filename [, int use_include_path [, resource context]] ) $file_contents = file('/path/to/your/file.txt'); loop over file_contents, skipping elements you don't want. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted May 29, 2008 Share Posted May 29, 2008 file() opens a file and creates an array who's elements are the lines of that file: $file = file('schools.txt'); echo '<pre>'.print_r($file,1).'</pre>'; Quote Link to comment Share on other sites More sharing options...
prudens Posted May 29, 2008 Author Share Posted May 29, 2008 Thanks, how do I skip the <html> tags? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted May 29, 2008 Share Posted May 29, 2008 Probably have to read it into a sting, strip the HTML tags, explode by the new lines, then remove empty elements: <?php $file = file_get_contents('file.txt'); $file = strip_tags($file); $lines = explode("\n",$file); foreach($lines as $k=>$v){ $v = trim($v); if(empty($v)){ unset($lines[$k]); } } echo '<pre>'.print_r($lines,1).'<pre>'; ?> Actually, it would be easier to trim out the unnecessary white space first: <?php $file = file_get_contents('file.txt'); $file = trim(strip_tags($file)); $lines = explode("\n",$file); echo '<pre>'.print_r($lines,1).'<pre>'; ?> Quote Link to comment Share on other sites More sharing options...
prudens Posted May 29, 2008 Author Share Posted May 29, 2008 Would it be smarter to store the "schools" in a mySQL table or in a text file?? It's gonna get really big... Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted May 29, 2008 Share Posted May 29, 2008 Would be easier to store it in a database. It is, afterall, what databases are designed to be used for. Though a simple read of a text file is not difficult, things get harder when you wish to modify a school's name or delete it. Or the requirements could change, and you may wish to store added information about each school. A database is a more 'future proof' solution. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.