Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * This script will remove transactions from a given GNUcash book file. This was useful to me
- * when I deleted a bunch of accounts and then was stuck with thousands of entries under
- * the "Imbalance" category. AFAIK, there is no official way to perform this action.
- *
- * To use:
- * 1. Make a copy of your gnucash file with a gzip extension: `cp my_file.gnucash my_file.gz`
- * 2. Un-gzip it: `gzip -d my_file.gz`
- * 3. Open it in a text editor and look for the <gnc:account> block for the account in question.
- * Usually you can just text search for the account name.
- * 4. Copy down the GUID for the account, it will look something like:
- * <act:id type="guid">585c23271c91aa83b48179a21b12683b</act:id>
- * 5. Modify the variables below based on the last few steps.
- * 6. Run the PHP script in the same directory as the GNUcash file: `php extract_transactions.php`
- * 7. Gzip the resulting file (it is the same name as the original with a '.out' extension on it)
- * and rename it to `whatever_you_want.gnucash`.
- */
- /* XXX ** Fill out these variables: **********/
- $filename = 'my_file';
- $guid = '';
- /*********************************************/
- $file = file($filename);
- $file_out = fopen($filename.'.out', 'w');
- // States:
- // 0 - outside transaction
- // 1 - inside transaction
- // 2 - inside bad transaction
- // 3 - exiting bad transaction
- // 4 - exiting good transaction
- $state = 0;
- $str_trn_start = 'gnc:transaction';
- $str_trn_stop = '/gnc:transaction';
- $buffer = '';
- foreach ($file as $line_num => $line) {
- if ($state == 0) {
- if (strpos($line, $str_trn_start)) {
- // We're entering a transaction
- $state = 1;
- } else {
- // We left a normal good line, write it
- fwrite($file_out, $line);
- }
- }
- // Buffer-building states
- if ($state == 1) {
- // if we're in a potentially good transaction, add the line to the buffer
- $buffer .= $line;
- // Check if this is a bad transaction
- if (strpos($line, $guid)) {
- $state = 2;
- }
- // Check if we're leaving this transaction
- if (strpos($line, $str_trn_stop)) {
- $state = 4;
- }
- }
- elseif ($state == 2) {
- // inside bad transaction
- // Check if we're leaving this transaction
- if (strpos($line, $str_trn_stop)) {
- $state = 3;
- }
- }
- // Buffer writing states
- if ($state == 3) {
- // We left a bad transaction. Clear the buffer and move on.
- $buffer = '';
- $state = 0;
- }
- elseif ($state == 4) {
- // We've left a good transaction, write the buffer
- echo "writing good transaction to file\n";
- fwrite($file_out, $buffer);
- $buffer = '';
- $state = 0;
- }
- //echo $state;
- }
- fclose($file_out);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement