// --- array to XML ---
// function defination to convert array to xml
public function arrayToXml( &$data_xml, $data_list=array() ) {
foreach( $data_list as $key => $value ) {
if (trim($key)=='')
{continue;}
if( is_array($value) ) {
if( is_numeric($key) ){
$key = "item".$key; //dealing with <0/>..<n/> issues
}
$new_child = $data_xml->addChild($key);
$this->arrayToXml($new_child, $value);
} else {
if (is_numeric($key)) {// if the key is an integer, it needs text
$key = "key".$key;
}
$new_child = $data_xml->addChild("$key", htmlspecialchars("$value"));
}
}
}
// array to csv / json
public function csvStrToCsv($input=array(), $delimiter = ',', $enclosure = '"')
{
if (!is_array($input))
{return false;}
foreach($input as $key=>$value)
{
if (is_array($value))
{
$input[$key] = $this->csvStrToCsv($value, $delimiter, $enclosure);
}
}
$fp = fopen('php://temp', 'r+'); // Open a memory "file" for read/write...
fputcsv($fp, $input, $delimiter, $enclosure);
rewind($fp);
$data = fread($fp, 1048576);
fclose($fp);
return rtrim($data, "\n");
}
public function format($data=array(), $format='') // output format php array (/ json / xml / csv - not implement)
{
if ($format=='')
{
return $data;
}
elseif ($format=='csv')
{
$content = '';
$valenc = "\"";
$coldel = ";";
$rowdel = "\n";
// $rowdel = "<br>"; // for html/text
foreach ($data as $row)
{
$content .= $this->csvStrToCsv($row, $coldel) . $rowdel; // excel csv, del=; enc=" row=\n
}
return $content;
}
elseif ($format=='json')
{
return json_encode($data);
}
elseif ($format=='xml')
{
$xml = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
$this->arrayToXml($xml, $data);
return $xml->asXML();
}
}
// --- csv content to array ---
// https://www.php.net/…r-getcsv.php
public function import($content='')
{
$p = $this->parse;
list($row, $col, $enc, $esc) = array($p['row'], $p['col'], $p['enc'], $p['esc']);
$row_list = str_getcsv($content, $row); // parse the rows
$content = null;
foreach($row_list as &$row)
{
$row = str_getcsv($row, $col, $enc, $esc); //parse the items in rows
}
return $row_list;
}