07-17-2008, 06:27 PM
|
#3 (permalink)
|
|
The Contributor
Join Date: Jan 2008
Location: England, UK
Posts: 83
Thanks: 3
|
I would use explode to do this, although fscanf looks a lot easier - I've never seen it before and I'd recommend it now!
PHP Code:
<?php
/** * Explode method */
// First explode the file into seperate lines and loop through to remove empty lines, etc $file = file_get_contents('file.txt'); $file = explode("\n", $file);
$lines = array();
foreach($file as $line) { // Checks a line is not empty (after whitespace is removed) or not a comment (using .ini style comments) if(!empty(trim($line)) && substr($line, 0, 1) != ';') { $lines[] = trim($line); } }
// Next parse the data from the line and add to the $data array $data = array(); foreach($lines as $line) { $line = explode('=>', $line); // Check the line is an array and hasn't done something silly if(is_array($line)) { $data[] = $line; } }
print_r($data);
/** * fscanf method */ $file = fopen('file.txt', 'r');
$data_array = array();
while($data = fscanf($file, '%s=>%s=>%s')) { list($name1, $name2, $file) = $data; // Example $data_array[$name1] = array($name2, $file); }
fclose($file);
print_r($data_array);
?>
As you can see the explosion method is much more memory intensive but shows you how a file could be parsed. fscanf is much more simple to use.
|
|
|
|