將與一個非常簡單的面向靜態行解析器工作。每條線都將解析的數據累積到一個數組()中。當某些事情告訴你正在創建一個新記錄時,你會轉儲你解析的內容並重新開始。
面向行的解析器具有很好的屬性:它們只需要很少的內存以及最重要的內存。他們可以在沒有任何汗水的情況下繼續使用千兆字節的數據。我正在管理大量生產服務器,沒有什麼比那些將整個文件拖入內存的腳本更糟糕了(然後用解析的內容填充數組,這需要比原始文件大小多兩倍的內存)。
這工作和主要是牢不可破:
<?php
$in_name = 'in.txt';
$in = fopen($in_name, 'r') or die();
function dump_record($r) {
print_r($r);
}
$current = array();
while ($line = fgets($in)) {
/* Skip empty lines (any number of whitespaces is 'empty' */
if (preg_match('/^\s*$/', $line)) continue;
/* Search for '123. <value> ' stanzas */
if (preg_match('/^(\d+)\.\s+(.*)\s*$/', $line, $start)) {
/* If we already parsed a record, this is the time to dump it */
if (!empty($current)) dump_record($current);
/* Let's start the new record */
$current = array('id' => $start[1]);
}
else if (preg_match('/^(.*):\s+(.*)\s*/', $line, $keyval)) {
/* Otherwise parse a plain 'key: value' stanza */
$current[ $keyval[1] ] = $keyval[2];
}
else {
error_log("parsing error: '$line'");
}
}
/* Don't forget to dump the last parsed record, situation
* we only detect at EOF (end of file) */
if (!empty($current)) dump_record($current);
fclose($in);
?>
Obvously你需要的東西適合你的口味在function dump_record
,如打印正確格式化INSERT SQL語句。
一個簡單而應該足夠好。 –