<html>

<head>
<title>XML2CSV</title>
</head>

<body>

<?php

$container="DocDetail";
require "./settings.inc";
require "./translit.php";
$titles=Array();
$ff=0;
$handle=opendir("./XML");
while (($file = readdir($handle))!==FALSE) {
if(strtolower(substr($file,-4))==".xml") {


echo "<pre><strong>PREPARE $file ...</strong>\n";
//Категории
if(file_exists("./XML/".$file.".scheme")) {
$sh=file("./XML/".$file.".scheme");
$tag=trim(array_shift($sh));
if($tag!="") {
echo "Found scheme, container tag=".$tag."\n";
$container=$tag;
}
}
$dir=".";
$st2="";

$f=fopen("./XML/".$file,"rt");
$f2=fopen("./TMP/".$file,"w");
$i=0;
while(!feof($f)) {
$i++;
$st=trim(fgets($f));
if($st!="") {
if ($charset=="") {
preg_match( '@<\?xml.+encoding="([^\s"]+)@si', $st, $matches );
if ( isset( $matches[1] ) )
$charset = strtoupper($matches[1]);
}
preparexml("$container",$st,$f2);
}
}
fclose($f2);
fclose($f);

$f=fopen("./TMP/".$file,"rt");
$f2=fopen("./RESULT/".$file.".csv","w");
$i=0;
while(!feof($f)) {
$i++;
$st=trim(fgets($f));
if($st!="") {
unset($arr);
$arr=parsexmlstr("$container", $st,$f2);
//print_r($arr);
$st2="";
foreach($sh as $val) {
eval("\$var=@\$arr[children]".trim($val).";");
if(!is_array($var)) {
$st2.=$var."|";
}
}
fputs($f2,utf8win1251($st2)."\n");
}
}
fclose($f2);
fclose($f);
@unlink("./TMP/".$file);
}
}
closedir($handle);
echo "<h1>OK</h1>";
echo "<h2>STEP 2</h2>";
require ("./step2.php");
echo "<h1>OK</h1>";
?>
</body>

</html>