i need update file using php
sample file:
#start# no. of records: 2 name: name, age: 18, date: 2013-07-11|| name: 2nd name, age: 28, date: 2013-07-11|| #end#
i need edit 'no. of records' on each time add record on file. , record needs before '#end#'
i'm using
$handle = fopen($file, 'a'); $data = ....... fwrite($handle, $data);
to add records
how can edit 'no. of records' & add data before '#end#'?
instead of modifying file parse it, change data in php rewrite file after that.
to achieve this, firstly create function parses input php arrays:
function parse($file) { $records = array(); foreach(file($file) $line) { if(preg_match('~^name: (.*),~', $line, $matches)) { $record = array('name' => $matches[1]); } if(preg_match('~^age: (.*),~', $line, $matches)) { $record ['age'] = $matches[1]; } if(preg_match('~^date: (.*)\|\|~', $line, $matches)) { $record ['date'] = $matches[1]; $records [] = $record; } } return $records; }
secondly create function flattens arrays same file format again:
function flatten($records, $file) { $str = '#start#'; $str .= "\n\n"; $str .= 'no. of records: ' . count($records) . "\n\n"; foreach($records $record) { $str .= 'name: ' . $record['name'] . ",\n"; $str .= 'age: ' . $record['name'] . ",\n"; $str .= 'date: ' . $record['name'] . "||\n\n"; } file_put_contents($file, $str . '#end#'); }
then use this:
$records = parse('your.file'); var_dump($records); $records []= array( 'name' => 'hek2mgl', 'age' => '36', 'date' => '07/11/2013' ); flatten($records, 'your.file');
Comments
Post a Comment