<?php
// csv_via_xml_report.php
// Create CSV report via XML input
// RJM Programming
// September, 2018

 $line='';
 $numargs=-1;
 $gxml="";
 $pxml="";
 $ziparr = array();
 $detailrec='';
 
 function outinalways($inh) {
     $huhr='';
     $wo=false;
     for ($iu=0; $iu<strlen($inh); $iu++) {
       if (substr($inh, $iu, 1) == '>') {
         $wo=true;
       } else if (substr($inh, $iu, 1) == '<') {
         $wo=false;
       } else if ($wo) {
         $huhr.=substr($inh, $iu, 1);
       }
     }
     return $huhr;
 }
 
 
 function outin($inh) {
   global $numargs;
   if ($numargs <= 0) {
     return $inh;
   } else {
     $huhr='';
     $wo=false;
     $inh=str_replace("</title>","\n",str_replace("</p>","\n",str_replace("</tr>","\n",str_replace("<br>","\n",$inh))));
     for ($iu=0; $iu<strlen($inh); $iu++) {
       if (substr($inh, $iu, 1) == '>') {
         $wo=true;
       } else if (substr($inh, $iu, 1) == '<') {
         $wo=false;
       } else if ($wo) {
         $huhr.=substr($inh, $iu, 1);
       }
     }
     return $huhr;
   }
 }
 
 function userdef($pvsg, $infis, $outfis, $defhdr) {
    global $detailrec;
    $firstoffs = array();
    $counts = array();
    $delm="";
    $hdelm="";
    $xcnt=0;
    $minrows=-1;
    $maxcols=0;
    $ourhdr=$defhdr;
    $thisrows=0;
    $xcont=file_get_contents($infis);
    $ix=0;
    if (strtoupper($pvsg) == "GET") {
      $ourhdr="";
      while (isset($_GET['dheader' . $xcnt])) {
        $ourhdr.=$hdelm . '"' . str_replace("+"," ",urldecode($_GET['dheader' . $xcnt])) . '"';
        $hdelm=",";
        $hdrhuh=str_replace("+"," ",urldecode($_GET['dprefix' . $xcnt]));
        while (strpos($hdrhuh, "&v[") !== false) {
          $ix=explode("]", explode("&v[", $hdrhuh)[1])[0];
          $hdrhuh=str_replace("&v[" . $ix . "]", $firstoffs[-1 + $ix], $hdrhuh);
        }
        $thisrows=explode($hdrhuh, $xcont);
        array_push($counts, (-1 + sizeof($thisrows)));
        if (sizeof($thisrows) == 1) {
          array_push($firstoffs, "");
          if ($minrows < 0) {
            $minrows=0;
          } else {
            $minrows=1;
          }
        } else if ($minrows < 0) {
          array_push($firstoffs, explode(str_replace("+"," ",urldecode($_GET['dsuffix' . $xcnt])), $thisrows[1])[0]);
          $minrows=-1 + sizeof($thisrows);
        } else if (sizeof($thisrows) <= $minrows) {
          array_push($firstoffs, explode(str_replace("+"," ",urldecode($_GET['dsuffix' . $xcnt])), $thisrows[1])[0]);
          $minrows=-1 + sizeof($thisrows);
        }
        $xcnt++;
        $maxcols=$xcnt;
      }
    } else if (strtoupper($pvsg) == "POST") {
      $ourhdr="";
      while (isset($_POST['dheader' . $xcnt])) {
        $ourhdr.=$hdelm . '"' . str_replace("+"," ",urldecode($_POST['dheader' . $xcnt])) . '"';
        $hdelm=",";
        $hdrhuh=str_replace("+"," ",urldecode($_POST['dprefix' . $xcnt]));
        while (strpos($hdrhuh, "&v[") !== false) {
          $ix=explode("]", explode("&v[", $hdrhuh)[1])[0];
          $hdrhuh=str_replace("&v[" . $ix . "]", $firstoffs[-1 + $ix], $hdrhuh);
        }
        $thisrows=explode($hdrhuh, $xcont);
        array_push($counts, (-1 + sizeof($thisrows)));
        if (sizeof($thisrows) == 1) {
          array_push($firstoffs, "");
          if ($minrows < 0) {
            $minrows=0;
          } else {
            $minrows=1;
          }
        } else if ($minrows < 0) {
          array_push($firstoffs, explode(str_replace("+"," ",urldecode($_POST['dsuffix' . $xcnt])), $thisrows[1])[0]);
          $minrows=-1 + sizeof($thisrows);
        } else if (sizeof($thisrows) <= $minrows) {
          array_push($firstoffs, explode(str_replace("+"," ",urldecode($_POST['dsuffix' . $xcnt])), $thisrows[1])[0]);
          $minrows=-1 + sizeof($thisrows);
        }
        $xcnt++;
        $maxcols=$xcnt;
      }
    }
    $xcnt=0;
    if (strtoupper($pvsg) == "GET") {
      $detailrec="";
      $delm="";
      for ($iyu=0; $iyu<$minrows; $iyu++) {
        if ($iyu == 0 && 1 == 3) {
         for ($ixu=0; $ixu<$maxcols; $ixu++) {
          $detailrec.=$delm . '"' . $firstoffs[$ixu] . '"';
          $delm=",";
         }
        } else {
         for ($ixu=0; $ixu<$maxcols; $ixu++) {
          if ($counts[$ixu] <= $iyu) { 
          $detailrec.=$delm . '""';
          $delm=",";
          } else {
          $hdrhuh=str_replace("+"," ",urldecode($_GET['dprefix' . $ixu]));
          while (strpos($hdrhuh, "&v[") !== false) {
            $ix=explode("]", explode("&v[", $hdrhuh)[1])[0];
            $hdrhuh=str_replace("&v[" . $ix . "]", $firstoffs[-1 + $ix], $hdrhuh);
          }
          $thisrows=explode($hdrhuh, $xcont);
          if (str_replace("</"," ",urldecode($_GET['dsuffix' . $ixu])) != urldecode($_GET['dsuffix' . $ixu])) {
          $detailrec.=$delm . '"' . outinalways(explode(str_replace("+"," ",urldecode($_GET['dsuffix' . $ixu])), $thisrows[1 + $iyu])[0]) . '"';
          } else {
          $detailrec.=$delm . '"' . explode(str_replace("+"," ",urldecode($_GET['dsuffix' . $ixu])), $thisrows[1 + $iyu])[0] . '"';
          }
          $delm=",";
          }
         }
        }
        $delm="\n";
      }
    } else if (strtoupper($pvsg) == "POST") {
      $detailrec="";
      $delm="";
      for ($iyu=0; $iyu<$minrows; $iyu++) {
        if ($iyu == 0 && 1 == 3) {
         for ($ixu=0; $ixu<$maxcols; $ixu++) {
          $detailrec.=$delm . '"' . $firstoffs[$ixu] . '"';
          $delm=",";
         }
        } else {
         for ($ixu=0; $ixu<$maxcols; $ixu++) {
          if ($counts[$ixu] <= $iyu) { 
          $detailrec.=$delm . '""';
          $delm=",";
          } else {
          $hdrhuh=str_replace("+"," ",urldecode($_POST['dprefix' . $ixu]));
          while (strpos($hdrhuh, "&v[") !== false) {
            $ix=explode("]", explode("&v[", $hdrhuh)[1])[0];
            $hdrhuh=str_replace("&v[" . $ix . "]", $firstoffs[-1 + $ix], $hdrhuh);
          }
          $thisrows=explode($hdrhuh, $xcont);
          if (str_replace("</"," ",urldecode($_POST['dsuffix' . $ixu])) != urldecode($_POST['dsuffix' . $ixu])) {
          $detailrec.=$delm . '"' . outinalways(explode(str_replace("+"," ",urldecode($_POST['dsuffix' . $ixu])), $thisrows[1 + $iyu])[0]) . '"';
          } else {
          $detailrec.=$delm . '"' . explode(str_replace("+"," ",urldecode($_POST['dsuffix' . $ixu])), $thisrows[1 + $iyu])[0] . '"';
          }
          $delm=",";
          }
         }
        }
        $delm="\n";
      }
    }
    return $ourhdr;
 }
 
 function buttonize($inh) {
     $wo=false;
     $outsd="";
     $elecnt=0;
     $ioff=0;
     for ($iu=0; $iu<strlen($inh); $iu++) {
       if ($ioff > 0) {
         $ioff--;
       } else if (substr(($inh . "    "), $iu, 1) == "\n") {
         $outsd.=" ";
       } else if (substr(($inh . "        "), $iu, 8) == '&gt;&lt;') {
         $elecnt++;
         $wo=false;
         $ioff=7;
         $outsd.=substr($inh, $iu, 4) . '<span id="ss' . $elecnt . '">&lt;';
       } else if (substr(($inh . "    "), $iu, 4) == '&gt;') {
         $wo=true;
         $ioff=3;
         $outsd.=substr($inh, $iu, 4);
         $outsd.='</span><input title="Click here to define some delimitation rules nearby" style="border:2px solid red;" id="ii' . $elecnt . '" onclick="lookatthis(this);" type="button" value="';
         $elecnt++;
       } else if (substr(($inh . "    "), $iu, 4) == '&lt;') {
         if ($wo) { $outsd.='"></input>';  }
         $outsd.='<span id="ss' . $elecnt . '">';
         $wo=false;
         $ioff=3;
         $outsd.=substr($inh, $iu, 4);
       } else if ($wo) {
         $outsd.=substr($inh, $iu, 1);
       } else {
         $outsd.=substr($inh, $iu, 1);
       }
     }
     return str_replace("'", "' + String.fromCharCode(39) + '", str_replace("\n","<Br>",$outsd));
 }
 
 if (isset($_GET['xml'])) { // surfing the net
  $gxml=$_GET['xml'];
 } else if (isset($_POST['xml'])) { // surfing the net
  $pxml=$_POST['xml'];
 } else if (isset($argv)) { // command line
  $numargs = sizeof($argv);
  if ($numargs <= 1) {
   if (PHP_OS == 'WINNT') {
    echo '$ XML File(spec) or URL: ';
    $line = stream_get_line(STDIN, 1024, PHP_EOL);
   } else {
    $line = readline('$ XML File(spec) or URL: ');
   }
   $gxml=urlencode($line);
  } else {
   $gxml=$argv[1];
   array_push($ziparr, $argv[1]);
   for ($iu=2; $iu<$numargs; $iu++) {
    $gxml.=' ' . $argv[$iu];
    array_push($ziparr, $argv[$iu]);
   }
   $gxml=urlencode($gxml);
  }
 }
  
 $jobbits="Job Description Goes Here";  // fill this in
 if (isset($_GET['gtitle'])) {
    $jobbits=str_replace("+"," ",urldecode($_GET['gtitle']));
 } else if (isset($_POST['gtitle'])) {
    $jobbits=str_replace("+"," ",urldecode($_POST['gtitle']));
 }

 function oursimplexml_load_file($inxml) {
  global $detailrec;
  if (isset($_GET['generic']) || isset($_POST['generic'])) {
   return simplexml_load_file($inxml);
  } else {
   $outrpts=explode(".xm", str_replace(".XML",".xml",str_replace(".Xml",".xml",$inxml)));
   $outrpt="";
   if (sizeof($outrpts) > 1) {
     $bz="";
     $prebz=""; 
     $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     while (file_exists($outrpts[0] . ".csv" . $bz)) {
       if (("" . $bz) == "") {
         $prebz="_";
         $bz=1;
       } else {
         $bz++;
       }
       $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     }
   }
   // Start of business logic piecing together CSV report ... 
   $cont=file_get_contents($inxml);
   $detailrec='';
   $headerrec='';
   if (isset($_GET['dheader0'])) {
      $headerrec=userdef("GET", $inxml, $outrpt, '"col1label","col2label"');
   } else if (isset($_POST['dheader0'])) {
      $headerrec=userdef("POST", $inxml, $outrpt, '"col1label","col2label"');
   } else {
      $detailrec='"col1value","col2value"'; // you do more in depth work to get to this point via $cont
   }
   if (trim($detailrec) != "") {
     if ($headerrec == "") {
       $headerrec='"col1label","col2label"'; // you do more in depth work to get a header record as required via $cont
     }
     if ($outrpt != "" && 1 == 1) {
       if ($headerrec != "") { $headerrec.="\n";  }
       file_put_contents($outrpt, $headerrec . $detailrec);
       exit;
     } else {
       if ($headerrec != "") { $headerrec.="<br>";  }
       echo "<html><body><div>" . $headerrec . $detailrec . "</div></body></html>";
       return null;
     }
   }
   // End of business logic piecing together CSV report
   return null;
  }
 }

$genextra="";
if (isset($_GET['generic']) || isset($_POST['generic'])) {
  $genextra="<input type=hidden name=generic value=generic></input>";
}
$xmlstr="";
$outidea="outfile.csv";
$keep=true;
if (!isset($_GET['keep']) && !isset($_POST['keep'])) {
 $keep=false;
}
if ($gxml != "") {
 // add in file(spec) considerations here
 if (strpos(str_replace("+"," ",urldecode($gxml)), " ") !== false || strpos(str_replace("+"," ",urldecode($gxml)), "*") !== false || strpos(str_replace("+"," ",urldecode($gxml)), "%") !== false || strpos(str_replace("+"," ",urldecode($gxml)), "?") !== false) {
   $htmlis="<html><body><h1>XML to CSV <span id=dtitle contenteditable=true>" . $jobbits . "</span> Report Run ... </h1><div></div></body></html>";
   if (strpos(str_replace("+"," ",urldecode($gxml)), " ") !== false) {
   $inths=str_replace(" ",",",str_replace("+"," ",urldecode($gxml))); //$ziparr;
   } else {
   $inths=str_replace("+"," ",urldecode($gxml));
   }
   $intha=explode(",", $inths);
   for ($ii=0; $ii<sizeof($intha); $ii++) {
   $inth=$intha[$ii];
   foreach (glob($inth) as $xmlfil) {
     if (isset($_GET['usermenus']) || isset($_POST['usermenus'])) {
       echo "<html><head><scri" . "pt type='text/javascript'> 
       function popdiv() {
          if (parent.document.getElementById('fleshitout')) {
          if (parent.document.getElementById('fleshitout').innerHTML == '') {
            var dt='<input title=\"Job title\" name=gtitle id=gtitle type=text value=\"' + parent.document.getElementById('dtitle').innerHTML + '\"></input>';
            parent.document.getElementById('fleshitout').innerHTML='<hr><br><table style=width:100%; id=tfleshitout border=20><tr><th onclick=document.getElementById(\"ii0\").click();>Define Columns of Interest</th><th>Column Definition Basis</th></tr><tr><td id=lhs style=vertical-align:top;background-color:pink;>' + dt + '<br><div id=divlhs0></div></td><td id=tdfleshitout><div id=divfleshitout></div></td></tr></table>';
            parent.document.getElementById('divfleshitout').innerHTML='" . buttonize(str_replace(">","&gt;",str_replace("<","&lt;",file_get_contents($xmlfil)))) . "'; 
            parent.document.getElementById('xml').style.cursor='pointer';
            parent.document.getElementById('isubmit').style.cursor='pointer';
          }
          }
       }
       </scr" . "ipt></head><body onload=popdiv();></body></html>";
       exit;
     }
     $bz="";
     $prebz=""; 
     $outrpts=explode(".xm", str_replace(".XML",".xml",str_replace(".Xml",".xml",$xmlfil)));
     $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     while (file_exists($outrpts[0] . ".csv" . $bz)) {
       if (("" . $bz) == "") {
         $prebz="_";
         $bz=1;
       } else {
         $bz++;
       }
       $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     }
     if ($numargs >= 1) {
     exec("php " . $argv[0] . ' "' . $xmlfil . '"'); 
     } else if (isset($_GET['dheader0']) || isset($_POST['dheader0'])) {

   //$cont=file_get_contents($xmlfil);
   $detailrec='';
   $headerrec='';
   if (isset($_GET['dheader0'])) {
      $headerrec=userdef("GET", $xmlfil, $outrpt, '"col1label","col2label"');
   } else if (isset($_POST['dheader0'])) {
      $headerrec=userdef("POST", $xmlfil, $outrpt, '"col1label","col2label"');
   } 
   if (trim($detailrec) != "" || $headerrec != "") {
     if ($headerrec == "") {
       $headerrec='"col1label","col2label"'; // you do more in depth work to get a header record as required via $cont
     }
     if ($outrpt != "" && 1 == 1) {
       if ($headerrec != "") { $headerrec.="\n";  }
       file_put_contents($outrpt, $headerrec . $detailrec);
     } 
   }
     } else {
     exec("curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?xml=' . urlencode($xmlfil)); 
     }
     if (file_exists($outrpt)) {
       if (isset($_GET['dheader0']) || isset($_POST['dheader0'])) {
        $htmlis=str_replace("</div>","<details style=background-color:yellow; open><summary style=background-color:pink;>Read " . $xmlfil . " as basis for" . " " . $jobbits . " report " . $outrpt . " for your perusal.</summary>" . str_replace("\n","<br>",file_get_contents($outrpt)) . "</details></div>",$htmlis);
        unlink($outrpt);
       } else {
        $htmlis=str_replace("</div>","Read " . $xmlfil . " as basis for" . " " . $jobbits . " report <a target=_blank title='" . $outrpt . "' href='" . $outrpt . "'>" . $outrpt . "</a> for your perusal.<br></div>",$htmlis);
       }
     } else {
       $htmlis=str_replace("</div>","Could not read " . $xmlfil . " as basis for" . " " . $jobbits . " report " . $outrpt . " successfully, alas.<br></div>",$htmlis);
     }
   }
   }
   echo outin($htmlis);
   exit;
 } 
 // end of file(spec) considerations above
 if (strpos(strtolower("~" . urldecode($gxml)), "~http") !== false) {
   $xmlstr=file_get_contents(urldecode($gxml));
   $outidea=explode("." . explode(".",urldecode($gxml))[-1 + sizeof(explode(".",urldecode($gxml)))], urldecode($gxml))[0];
   $outidea=explode("/", $outidea)[-1 + sizeof(explode("/", $outidea))];
   $outidea=explode(substr("\\",0,1), $outidea)[-1 + sizeof(explode(substr("\\",0,1), $outidea))];
   $outidea.=".csv";
 } else if (strpos(strtolower("~" . urldecode($gxml)), "~<") !== false) {
   $xmlstr=str_replace("+"," ",urldecode($gxml));
 }
 if ($xmlstr != "") {
   $xml = oursimplexml_load_string($xmlstr);
 } else if (file_exists(urldecode($gxml))) {
   $xmlstr=" ";
   $outidea=explode("." . explode(".",urldecode($gxml))[-1 + sizeof(explode(".",urldecode($gxml)))], urldecode($gxml))[0];
   $outidea=explode("/", $outidea)[-1 + sizeof(explode("/", $outidea))];
   $outidea=explode(substr("\\",0,1), $outidea)[-1 + sizeof(explode(substr("\\",0,1), $outidea))];
   $outidea.=".csv";
   $xml = oursimplexml_load_file(urldecode($gxml));
 }
} else if ($pxml != '') {
 // add in file(spec) considerations here
 if (strpos(str_replace("+"," ",urldecode($pxml)), "*") !== false || strpos(str_replace("+"," ",urldecode($pxml)), "%") !== false || strpos(str_replace("+"," ",urldecode($pxml)), "?") !== false) {
   $htmlis="<html><body><h1>XML to CSV <span id=dtitle contenteditable=true>" . $jobbits . "</span> Report Run ...</h1><div></div></body></html>";
   if (strpos(str_replace("+"," ",urldecode($pxml)), " ") !== false) {
   $inths=str_replace(" ",",",str_replace("+"," ",urldecode($gxml))); //$ziparr;
   } else {
   $inths=str_replace("+"," ",urldecode($pxml));
   }
   $intha=explode(",", $inths);
   for ($ii=0; $ii<sizeof($intha); $ii++) {
   $inth=$intha[$ii];
   foreach (glob($inth) as $xmlfil) {
     if (isset($_GET['usermenus']) || isset($_POST['usermenus'])) {
       echo "<html><head><scri" . "pt type='text/javascript'> 
       function popdiv() {
          if (parent.document.getElementById('fleshitout')) {
          if (parent.document.getElementById('fleshitout').innerHTML == '') {
            var dt='<input title=\"Job title\" name=gtitle id=gtitle type=text value=\"' + parent.document.getElementById('dtitle').innerHTML + '\"></input>';
            parent.document.getElementById('fleshitout').innerHTML='<hr><br><table style=width:100%; id=tfleshitout border=20><tr><th onclick=document.getElementById(\"ii0\").click();>Define Columns of Interest</th><th>Column Definition Basis</th></tr><tr><td id=lhs style=vertical-align:top;background-color:pink;>' + dt + '<br><div id=divlhs0></div></td><td id=tdfleshitout><div id=divfleshitout></div></td></tr></table>';
            parent.document.getElementById('divfleshitout').innerHTML='" . buttonize(str_replace(">","&gt;",str_replace("<","&lt;",file_get_contents($xmlfil)))) . "'; 
            parent.document.getElementById('xml').style.cursor='pointer';
            parent.document.getElementById('isubmit').style.cursor='pointer';
          }
          }
       }
       </scr" . "ipt></head><body onload=popdiv();></body></html>";
       exit;
     }
     $bz="";
     $prebz=""; 
     $outrpts=explode(".xm", str_replace(".XML",".xml",str_replace(".Xml",".xml",$xmlfil)));
     $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     while (file_exists($outrpts[0] . ".csv" . $bz)) {
       if (("" . $bz) == "") {
         $prebz="_";
         $bz=1;
       } else {
         $bz++;
       }
       $outrpt=$outrpts[0] . $prebz . $bz . ".csv";
     }
     if ($numargs >= 1) {
     exec("php " . $argv[0] . ' "' . $xmlfil . '"'); 
     } else if (isset($_GET['dheader0']) || isset($_POST['dheader0'])) {

   //$cont=file_get_contents($xmlfil);
   $detailrec='';
   $headerrec='';
   if (isset($_GET['dheader0'])) {
      $headerrec=userdef("GET", $xmlfil, $outrpt, '"col1label","col2label"');
   } else if (isset($_POST['dheader0'])) {
      $headerrec=userdef("POST", $xmlfil, $outrpt, '"col1label","col2label"');
   } 
   if (trim($detailrec) != "" || $headerrec != "") {
     if ($headerrec == "") {
       $headerrec='"col1label","col2label"'; // you do more in depth work to get a header record as required via $cont
     }
     if ($outrpt != "" && 1 == 1) {
       if ($headerrec != "") { $headerrec.="\n";  }
       file_put_contents($outrpt, $headerrec . $detailrec);
     } 
   }
     } else {
     exec("curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?xml=' . urlencode($xmlfil)); 
     }
     if (file_exists($outrpt)) {
       if (isset($_GET['dheader0']) || isset($_POST['dheader0'])) {
        $htmlis=str_replace("</div>","<details style=background-color:yellow; open><summary style=background-color:pink;>Read " . $xmlfil . " as basis for" . " " . $jobbits . " report " . $outrpt . " for your perusal.</summary>" . str_replace("\n","<br>",file_get_contents($outrpt)) . "</details></div>",$htmlis);
        unlink($outrpt);
       } else {
        $htmlis=str_replace("</div>","Read " . $xmlfil . " as basis for" . " " . $jobbits . " report <a target=_blank title='" . $outrpt . "' href='" . $outrpt . "'>" . $outrpt . "</a> for your perusal.<br></div>",$htmlis);
       }
     } else {
       $htmlis=str_replace("</div>","Could not read " . $xmlfil . " as basis for" . " " . $jobbits . " report " . $outrpt . " successfully, alas.<br></div>",$htmlis);
     }
   }
   }
   echo $htmlis;
   exit;
 } 
 // end of file(spec) considerations above
 if (strpos(strtolower("~" . urldecode($pxml)), "~http") !== false) {
   $xmlstr=file_get_contents(urldecode($pxml));
   $outidea=explode("." . explode(".",urldecode($pxml))[-1 + sizeof(explode(".",urldecode($pxml)))], urldecode($pxml))[0];
   $outidea=explode("/", $outidea)[-1 + sizeof(explode("/", $outidea))];
   $outidea=explode(substr("\\",0,1), $outidea)[-1 + sizeof(explode(substr("\\",0,1), $outidea))];
   $outidea.=".csv";
 } else if (strpos(strtolower("~" . urldecode($pxml)), "~<") !== false) {
   $xmlstr=str_replace("+"," ",urldecode($pxml));
 }
 if ($xmlstr != "") {
   $xml = oursimplexml_load_string($xmlstr);
 } else if (file_exists(urldecode($pxml))) { 
   $xmlstr=" ";
   $outidea=explode("." . explode(".",urldecode($pxml))[-1 + sizeof(explode(".",urldecode($pxml)))], urldecode($pxml))[0];
   $outidea=explode("/", $outidea)[-1 + sizeof(explode("/", $outidea))];
   $outidea=explode(substr("\\",0,1), $outidea)[-1 + sizeof(explode(substr("\\",0,1), $outidea))];
   $outidea.=".csv";
   $xml = oursimplexml_load_file(urldecode($pxml));
 }
}

if ($xmlstr != "") {
 if ($xml) {
 while (file_exists($outidea)) {
  $outidea=str_replace(".csv","1.csv",$outidea);
 }
 $outstream = fopen($outidea,'w');
 $header=false;
 foreach($xml as $k=>$details) {
    if (!$header) {
        $harr=array_keys(get_object_vars($details));
        if (sizeof($harr) != 0) {
         fputcsv($outstream,$harr);
         $header=true;
        }
    }
    $harr=get_object_vars($details);
    if (sizeof($harr) != 0) fputcsv($outstream,$harr);
 }
 fclose($outstream);
 //$csvstr=preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "",file_get_contents($outidea));
 //$csvstr=preg_replace("/(^[\n]*|[\n]+)[\s\t]*[\n]+/", "",$csvstr);
 $csvstr=file_get_contents($outidea);
 if (isset($_GET['download']) || isset($_POST['download'])) {
  echo outin("<!doctype html><html><head><title>XML to CSV " . $jobbits . " Report - RJM Programming - September, 2018</title>
 <script type='text/javascript'>
 var cold=[], icold=-1;
 function lookatthis(iiso) {
   if (icold < 0) {
     icold=0;
     document.getElementById('lhs').innerHTML+='<br><br>' + eval(1 + icold) + ': <input placeholder=\"Prefixing delimitation\" id=dprefix' + icold + ' type=text></input><br><input placeholder=\"Suffixing delimitation\" id=dsuffix' + icold + ' type=text></input>';
   } else if (!document.getElementById('dprefix' + icold)) {
     document.getElementById('lhs').innerHTML+='<br><br>' + eval(1 + icold) + ': <input placeholder=\"Prefixing delimitation\" id=dprefix' + icold + ' type=text></input><br><input placeholder=\"Suffixing delimitation\" id=dsuffix' + icold + ' type=text></input>';
   }
   var addto=prompt(iiso.value + ' appears after ' + document.getElementById('ss' + iiso.id.replace('ii','')).innerHTML.replace('&gt;','>').replace('&lt;','<') + String.fromCharCode(10) + String.fromCharCode(10) + 'Optionally enter a prefixing delimiter idea (number ' + eval(1 + icold) + '), and if it ends with double quote we will use a suffixing delimiter of double quote, else if you end it with something like </xxx> we will extract innerHTML up to </xxx> and if you involve &v[3] type bits that means replace the &v[3] with the value found at column 3 definition output value.', '');
   if (addto == null) { addto=''; }
   if (addto != '') {
     if (addto.indexOf('></') != -1) {
       document.getElementById('dsuffix' + icold).value='</' + addto.split('></')[1];
       document.getElementById('dprefix' + icold).value=addto.replace(document.getElementById('dsuffix' + icold).value,'');
       icold++;
     } else if ((addto + '~').indexOf(String.fromCharCode(34) + '~') != -1) {
       document.getElementById('dsuffix' + icold).value=String.fromCharCode(34);
       document.getElementById('dprefix' + icold).value=addto;
       icold++;
     } else {
       document.getElementById('dsuffix' + icold).value=String.fromCharCode(60);
       document.getElementById('dprefix' + icold).value=addto;
       icold++;
     }
   }
 }
 </script>
 </head>
 <body>
 <h1 id='myh1'>XML to CSV <span id=dtitle contenteditable=true>" . $jobbits . "</span> <a href='" . $outidea . "' download>" . $outidea . "</a></h1>
 <h3>RJM Programming - August, 2018</h3><br><br> 
 <form action='./csv_via_xml_report.php' method='GET'>
 XML File(spec) or URL: <input onblur=\"if (this.value.length > 0) { this.style.cursor='progress'; document.getElementById('isubmit').style.cursor='progress'; document.getElementById('ifleshitout').src=document.URL.split('#')[0].split('?')[0] + '?usermenus=y&xml=' + encodeURIComponent(this.value);  } \" type='text' name='xml' id='xml' value=''></input><br><br> 
 <input style='background-color:yellow;' id=isubmit type='submit' value='Convert to CSV " . $jobbits . " Report'></input>" . $genextra . "
 <div id=fleshitout></div>
 </form>
 <iframe src='' style='display:none;' id=ifleshitout></iframe>
 </body></html>");
 }
 } else {
  if (!$keep) {
   unlink($outidea);
   header('Content-type: text/csv');
   echo $csvstr;
   exit;
  } else {
   if (isset($_GET['keep'])) {
    if (urldecode($_GET['keep']) == 'keep') {
     unlink($outidea);
     echo outin("<!doctype html><html><head><title>XML to CSV " . $jobbits . " Report - RJM Programming - September, 2018</title>
 <script type='text/javascript'>
  function onld() {
    if (parent.document) {
    if (parent.document.getElementById('keep')) {
      parent.document.getElementById('keep').value=document.URL.split('#')[0].split('?')[0].split('csv_via_xml_report.php')[0] + '" . $outidea . "';
      if (parent.document.getElementById('xml')) {
        parent.document.getElementById('xml').value='" . str_replace('"',"' + String.fromCharCode(34) + '",str_replace("\n","' + String.fromCharCode(10) + '",str_replace("'","' + String.fromCharCode(39) + '",$csvstr))) . "';
      }
      /" . "/ if (parent.document.getElementById('myxmliframe')) {
      /" . "/ parent.document.getElementById('myxmliframe').src=document.URL.split('#')[0].split('?')[0].split('csv_via_xml_report.php')[0] + '" . $outidea . "';
      /" . "/ }
    }
    }
  }
 </script>
 </head>
 <body onload='onld();'></body></html>");
    } else {
     header('Content-type: text/csv');
     echo $csvstr;
     exit;
    }
   } else if (isset($_POST['keep'])) {
    if (urldecode($_POST['keep']) == 'keep') {
     unlink($outidea);
     echo outin("<!doctype html><html><head><title>XML to CSV " . $jobbits . " Report - RJM Programming - September, 2018</title>
 <script type='text/javascript'>
  function onld() {
    if (parent.document) {
    if (parent.document.getElementById('keep')) {
      parent.document.getElementById('keep').value=document.URL.split('#')[0].split('?')[0].split('csv_via_xml_report.php')[0] + '" . $outidea . "';
      if (parent.document.getElementById('xml')) {
        parent.document.getElementById('xml').value='" . str_replace('"',"' + String.fromCharCode(34) + '",str_replace("\n","' + String.fromCharCode(10) + '",str_replace("'","' + String.fromCharCode(39) + '",$csvstr))) . "';
      }
      /" . "/ if (parent.document.getElementById('myxmliframe')) {
      /" . "/   parent.document.getElementById('myxmliframe').src=document.URL.split('#')[0].split('?')[0].split('csv_via_xml_report.php')[0] + '" . $outidea . "';
      /" . "/ }
    }
    }
  }
 </script>
 </head>
 <body onload='onld();'></body></html>");
    } else {
     header('Content-type: text/csv');
     echo $csvstr;
     exit;
    }
   }
  } 
 }
} else if ($numargs <= 0) {
 echo outin("<!doctype html><html><head><title>XML to CSV " . $jobbits . " Report - RJM Programming - September, 2018</title>
 <script type='text/javascript'>
 var cold=[], icold=-1;
 function lookatthis(iiso) {
   if (icold < 0) {
     icold=0;
     document.getElementById('divlhs' + icold).innerHTML='<br><br>' + eval(1 + icold) + ': <input placeholder=\"Header record column name\" name=dheader' + icold + ' id=dheader' + icold + ' type=text></input><br><input placeholder=\"Prefixing delimitation\" name=dprefix' + icold + ' id=dprefix' + icold + ' type=text></input><br><input placeholder=\"Suffixing delimitation\" name=dsuffix' + icold + ' id=dsuffix' + icold + ' type=text></input><div id=divlhs' + eval(1 + icold) + '></div>';
   } else {
     document.getElementById('divlhs' + icold).innerHTML='<br><br>' + eval(1 + icold) + ': <input placeholder=\"Header record column name\" name=dheader' + icold + ' id=dheader' + icold + ' type=text></input><br><input placeholder=\"Prefixing delimitation\" name=dprefix' + icold + ' id=dprefix' + icold + ' type=text></input><br><input placeholder=\"Suffixing delimitation\" name=dsuffix' + icold + ' id=dsuffix' + icold + ' type=text></input><div id=divlhs' + eval(1 + icold) + '></div>';
   }
   var addto=prompt(iiso.value + ' appears after ' + document.getElementById('ss' + iiso.id.replace('ii','')).innerHTML.replace('&gt;','>').replace('&lt;','<') + String.fromCharCode(10) + String.fromCharCode(10) + 'Optionally enter a prefixing delimiter idea (number ' + eval(1 + icold) + '), and if it ends with double quote we will use a suffixing delimiter of double quote, else if you end it with something like </xxx> we will extract innerHTML up to </xxx> and if you involve &v[3] type bits that means replace the &v[3] with the value found at column 3 definition output value.', '');
   if (addto == null) { addto=''; }
   if (addto != '') {
     if (addto.indexOf('></') != -1) {
       document.getElementById('dsuffix' + icold).value='</' + addto.split('></')[1];
       document.getElementById('dprefix' + icold).value=addto.replace(document.getElementById('dsuffix' + icold).value,'');
       icold++;
     } else if ((addto + '~').indexOf(String.fromCharCode(34) + '~') != -1) {
       document.getElementById('dsuffix' + icold).value=String.fromCharCode(34);
       document.getElementById('dprefix' + icold).value=addto;
       icold++;
     } else {
       document.getElementById('dsuffix' + icold).value=String.fromCharCode(60);
       document.getElementById('dprefix' + icold).value=addto;
       icold++;
     }
   }
 }
 </script>
 </head>
 <body>
 <h1>XML to CSV <span id=dtitle contenteditable=true>" . $jobbits . "</span> Report</h1>
 <h3>RJM Programming - September, 2018</h3><br><br> 
 <form action='./csv_via_xml_report.php' method='GET'>
 XML File(spec) or URL: <input onblur=\"if (this.value.length > 0) { this.style.cursor='progress';  document.getElementById('isubmit').style.cursor='progress'; document.getElementById('ifleshitout').src=document.URL.split('#')[0].split('?')[0] + '?usermenus=y&xml=' + encodeURIComponent(this.value);  } \" type='text' name='xml' id='xml' value=''></input><br><br> 
 <input style='background-color:yellow;' type='submit' id=isubmit value='Convert to CSV " . $jobbits . " Report'></input>" . $genextra . "
 <div id=fleshitout></div>
 </form>
 <iframe src='' style='display:none;' id=ifleshitout></iframe>
 </body></html>");
}
?>
