#!/usr/bin/php -q * * $Platon: ovid-import.php,v 1.1 2002/06/30 20:40:11 jombik9 Exp $ * * Can be used as an example how to work with SQL database * via PEAR DB class in normal script runned from shell. */ // Data source name configuration $dsn = 'mysql://konzervativizmus:x@localhost/konzervativizmus'; $table = 'ovid_import'; $data_field = '__DATA'; // Command line arguments test if ($argc < 2) { echo "Usage: ./ovid_import.php \n"; die(); } $all = ''; $fp = null; $items = array(); echo "fopen(): "; if (($fp = fopen($argv[1], 'r')) == false) { echo "failed\n"; exit; } echo "OK\nreading: "; $all = fread($fp, filesize($argv[1])); $all = str_replace("\x00", "\x0a", $all); echo "OK\nfclose(): "; if (fclose($fp) == false) { echo "failed\n"; exit; } echo "OK\nsplit(): "; while (1) { $pos1 = strpos($all, '
');
	$pos2 = strpos($all, '
'); if ($pos1 === false || $pos2 === false) break; if ($pos1 > $pos2) die('synchronization error'); $items[] = substr($all, $pos1 + 5, $pos2 - $pos1 - 5); $all = substr($all, $pos2 + 6); } echo "OK\nRecords: " . count($items) . "\n"; //echo $items[0]; exit; // Vars $cols = array(); $rec = null; // PEAR DB class require_once 'DB.php'; require_once 'error.inc.php'; if (DB::isError($db = DB::connect($dsn))) { error($db); } $query = sprintf('DROP TABLE IF EXISTS %s', $table); if (DB::isError($res = $db->query($query))) { error($res); } $query = sprintf('CREATE TABLE %s (' .' id INT NOT NULL AUTO_INCREMENT,' .' %s TEXT, PRIMARY KEY (id))', $table, $data_field); if (DB::isError($res = $db->query($query))) { error($res); } foreach ($articles as $article) { // echo "current article:<$article>\n"; $article_ar = explode("\x0d", $article); $rec = array(); while (1) { $line = array_shift($article_ar); $line = trim($line); if ($line == '') { $rec[$data_field] = trim(join("\x0d", $article_ar)); break; } // Explode line to key (column name) and value $line_ar = explode(':', $line, 2); $key = trim($line_ar[0]); $key = preg_replace('/[^\w]/', '', $key); if (preg_match('/^[^a-zA-Z]/', $key)) $key = "X$key"; if (! in_array($key, $cols)) { // Creating new table column $cols[] = $key; $query = sprintf('ALTER TABLE %s ADD COLUMN %s TEXT', $table, $key); if (DB::isError($res = $db->query($query))) error($res); echo "Adding new column '$key'.\n"; } // Check if key already not exists in record if (isset($rec[$key])) { error(new PEAR_Error("Key '$key' already exists in record.", 1, PEAR_ERROR_RETURN)); } $rec[$key] = trim($line_ar[1]); } if (count($rec) <= 0) continue; // Inserting record into table $keys = ''; $vals = ''; foreach ($rec as $key => $val) { if (empty($val)) continue; if ($keys != '') $keys .= ', '; if ($vals != '') $vals .= ', '; $keys .= $key; $val = $db->quoteString($val); $vals .= "'$val'"; } if ($keys != '') { $query = sprintf('INSERT INTO %s (%s) VALUES (%s)', $table, $keys, $vals); if (DB::isError($res = $db->query($query))) error($res); } } ?>