<?php

$ISO_CHARS_1 = array (
    '&#261;' => 'ą',
    '&#260;' => 'Ą',
    '&#263;' => 'ć',
    '&#262;' => 'Ć',
    '&#281;' => 'ę',
    '&#280;' => 'Ę',
    '&#322;' => 'ł',
    '&#321;' => 'Ł',
    '&#324;' => 'ń',
    '&#323;' => 'Ń',
    '&#243;' => 'ó',
    '&#211;' => 'Ó',
    '&#347;' => 'ś',
    '&#346;' => 'Ś',
    '&#378;' => 'ź',
    '&#377;' => 'Ź',
    '&#380;' => 'ż',
    '&#379;' => 'Ż',
);

$ISO_CHARS_2 = array (
    '&#261' => 'ą',
    '&#260' => 'Ą',
    '&#263' => 'ć',
    '&#262' => 'Ć',
    '&#281' => 'ę',
    '&#280' => 'Ę',
    '&#322' => 'ł',
    '&#321' => 'Ł',
    '&#324' => 'ń',
    '&#323' => 'Ń',
    '&#243' => 'ó',
    '&#211' => 'Ó',
    '&#347' => 'ś',
    '&#346' => 'Ś',
    '&#378' => 'ź',
    '&#377' => 'Ź',
    '&#380' => 'ż',
    '&#379' => 'Ż',
);

//-------------------------------------------------------------------

// tac news.txt > invert-news.txt
$fn = fopen('invert-news.txt', 'r') or die('I can not open the file.');

$myFile = fopen('news-utf8.txt', 'w') or die('I can not open the file.');

while(!feof($fn))  {
    $rLine = fgets($fn);
    if ($rLine) {
        $rLine = mb_convert_encoding($rLine, 'UTF-8', 'ISO-8859-2');
        $rLine = strtr($rLine, $ISO_CHARS_1);
        $rLine = strtr($rLine, $ISO_CHARS_2);          
        $arrNews = explode('|', $rLine);       
        if ($arrNews[6] != '3'){
            $arrCategory = explode(',', $arrNews[6]);
            $category = $arrCategory[0];
            if (sizeof($arrCategory) == 2) {
                $category = $arrCategory[1];
            }
            $wLine = $arrNews[0]  // id
            . '|' .  $arrNews[1]  // author  
            . '|' .  $arrNews[2]  // title      
            . '|' .  $arrNews[3]  // content
            . '|' .  $category
            . PHP_EOL;
            fwrite($myFile, $wLine);
        }  else {                
            echo $arrNews[0]      // id
            . '|' . $arrNews[1]   // author
            . '|' . $arrNews[2]   // title      
            . '|' . $arrNews[6]   // status
            . PHP_EOL;
        }
    }
}

fclose($fn);
fclose($myFile);
