Core Coding®

PHP XML Generation

  PHP XML Generation
Quick and easy way to generate an xml feed from a database and read them back into an array.
function &last(&$array) {
if (!
count($array)) return null;
end($array);
return 
$array[key($array)];
}

function 
myParseXML(&$vals, &$dom, &$lev) {
   do {
       
$curr current($vals);
       
$lev $curr['level'];
       switch (
$curr['type']) {
           case 
'open':
               if (isset(
$dom[$curr['tag']])) {
                   
$tmp $dom[$curr['tag']];
                   if (!
$tmp['__multi'])
                       
$dom[$curr['tag']] = array('__multi' => true$tmp);
                   
array_push($dom[$curr['tag']], array());
                   
$new =& last($dom[$curr['tag']]);
               } else {
                   
$dom[$curr['tag']] = array();
                   
$new =& $dom[$curr['tag']];
               }
               
next($vals);
               
myParseXML(&$vals$new$lev);
               break;
           case 
'cdata':
               break;
           case 
'complete':
               if (!isset(
$dom[$curr['tag']]))
                   
$dom[$curr['tag']] = $curr['value'];
               else {
                   if (
is_array($dom[$curr['tag']]))
                       
array_push($dom[$curr['tag']] , $curr['value']);
                   else
                       
array_push($dom[$curr['tag']] = array($dom[$curr['tag']]) , $curr['value']);
               }
               break;
           case 
'close':
               return;
       }
   }
   while (
next($vals)!==FALSE);
}

function 
MyXMLtoArray($XML) {
       
$xml_parser xml_parser_create();
       
xml_parse_into_struct($xml_parser$XML$vals);
       
xml_parser_free($xml_parser);
       
reset($vals);
       
$dom = array(); $lev 0;
       
myParseXML($vals$dom$lev);
       return 
$dom;
}

function 
mysql2xml($sql$dblink) {
  
$counter 0;
  unset(
$fields);

  
$output "<?phpxml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
  
$output .= "<coredata>\n";

  
$res mysqli_query($dblink$sql);

  for (
$i=0$i<mysqli_num_fields($res); $i++)
    
$fields[] = mysqli_field_name($res$i);

  while (
$myr mysqli_fetch_array($res)) {
    
$counter++;

    
$output .= "  <entry$counter>\n";

    for (
$i=0$i<count($fields); $i++) {
      
$field $fields[$i];
      
$data $myr[$field];

      
$output .= "    <$field>$data</$field>\n";
    }

    
$output .= "  </entry$counter>\n";
  }

  
$output .= "</coredata>\n";

  return 
$output;
}


Go back to resources
Home Mail GitHub