How can I parse a java property file with php? -
hi have little problem in parsing java property file right way. need array every id, because want store in sql database. posting achieved until now. maybe have idea how right way:
content of 01.meta:
12345.filename=myfile.jpg 12345.path=files/myfile.jpg 12346.filename=myfile2.jpg 12346.path=files/myfile2.jpg
my php:
<?php $file_path = "files/01.meta"; $lines = explode("\n", trim(file_get_contents($file_path))); $properties = array(); foreach ($lines $line) { $line = trim($line); if (!$line || substr($line, 0, 1) == '#') // skip empty lines , comments continue; if (false !== ($pos = strpos($line, '='))) { $properties[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1)); } } print_r($properties); ?>
the result:
array ( [12345.filename] => myfile.jpg [12345.path] => files/myfile.jpg [12346.filename] => myfile2.jpg [12346.path] => files/myfile2.jpg )
what need:
array ( [id] => 12345 [filename] => myfile.jpg [path] => files/myfile.jpg ) array ( [id] => 12346 [filename] => myfile2.jpg [path] => files/myfile2.jpg )
a more elegant approach last 1 following:
$file_path = "files/01.meta"; $linesarray = file($file_path); // $linesarray array $properties = array(); foreach ($linesarray $line) { if (false !== ($pos = strpos($line, '='))) { $prop=array(); // create array ro receive 1 line $prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1)); $linecontarray = explode("=", $line); $identarray = explode(".", $linecontarray[0]); $ident = $identarray[0]; $type = $identarray[1]; $value = $linecontarray[1]; $found = 0; ($i=0; $i<count($properties); $i++) { if ($properties[$i]['id'] == $ident) { $properties[$i][$type]= $value; $found=1; break; } } if ($found == 0) { $properties[] = array('id' => $ident, $type => $value); } } }
this 1 has advantage elements in file can in arbitrary order.
Comments
Post a Comment