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

 $line='';
 $numargs=-1;
 $gxml="";
 $pxml="";
 $ziparr = array();
 
 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;
   }
 }
 
 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

 function oursimplexml_load_file($inxml) {
  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='';
   $detailrec='"col1value","col2value"'; // you do more in depth work to get to this point via $cont
   if (trim($detailrec) != "") {
     $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 " . $jobbits . " 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) {
     $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 {
     exec("curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?xml=' . urlencode($xmlfil)); 
     }
     if (file_exists($outrpt)) {
       $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 " . $jobbits . " 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) {
     $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 {
     exec("curl " . "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . explode("?",$_SERVER['REQUEST_URI'])[0] . '?xml=' . urlencode($xmlfil)); 
     }
     if (file_exists($outrpt)) {
       $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></head>
 <body>
 <h1 id='myh1'>XML to CSV <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 type='text' name='xml' value=''></input><br><br> 
 <input type='submit' value='Convert to CSV " . $jobbits . " Report'></input>" . $genextra . "
 </form>
 </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></head>
 <body>
 <h1>XML to CSV " . $jobbits . " 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 type='text' name='xml' value=''></input><br><br> 
 <input type='submit' value='Convert to CSV " . $jobbits . " Report'></input>" . $genextra . "
 </form>
 </body></html>");
}
?>
