Last active
August 29, 2015 14:17
-
-
Save artoodetoo/f143395965fb4fd2c705 to your computer and use it in GitHub Desktop.
Long XML file progress skeleton (CLI)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Parse XML item with attributes. Typically dumped table row. | |
* @param string $buffer XML item | |
* @return array false| array [name => value, ...] | |
*/ | |
function parse_row($buffer) | |
{ | |
$buffer = trim($buffer); | |
if (strpos($buffer, '<row') !== 0) { return false; } | |
$tmp = (array)simplexml_load_string($buffer); | |
return $tmp['@attributes']; | |
} | |
/** | |
* Insert into DB | |
* @param PDO $dbh Database connection | |
* @param string $table Table name | |
* @param array $attributes Assotiative array to insert | |
*/ | |
function insert($dbh, $table, $attributes) | |
{ | |
$fields = '`'.implode('`,`', array_keys($attributes)).'`'; | |
$places = implode(',', array_fill(0, count($attributes), '?')); | |
$sql = sprintf("INSERT INTO `%s`(%s) VALUES(%s)", $table, $fields, $places); | |
$sth = $dbh->prepare($sql); | |
$sth->execute(array_values($attributes)); | |
} | |
$filename = './myfile.txt'; | |
$fh = fopen($filename, 'r'); | |
echo "Process {$filename}...\n"; | |
$i = $j = 0; | |
$lastTime = microtime(true); | |
while (($buffer = fgets($fh)) !== false) { | |
// Show progress every 2 seconds | |
if (($now = microtime(true)) > $lastTime + 2) { | |
$lastTime = $now; | |
echo "{$i} lines read, {$j} applied\r"; | |
} | |
$attributes = parse_row($buffer); | |
if (!$attributes) { continue; } | |
// ... do something usefull ... | |
insert($dbh, 'mytable', $attributes); | |
++$j; | |
} | |
echo "\nTotal {$i} lines read and {$j} applied. All done!"; | |
fclose($fh); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment