<?php
//xml.php
//interpret XML-code
//written by Jaap van Ganswijk (JvG) <ganswijk@xs4all.nl>
//20090420/JvG, extracted from amazonv4.php

//convert an XML-string to an array
function xml2array($s) {
  if (
$Atmp1=explode('>',$s,2) and ereg('^<\?(xml .*)\?$',$Atmp1[0],$Atmp2)) {
    
$A['xml']=$Atmp2[1];
    
xml2array_sub($A,$Atmp1[1]);
  }
  return 
$A;
}

function 
xml2array_sub(&$A,$s) {
  global 
$error_msg;

  for (
$c=0;ereg('<([^<>/ ]*)( [^<>]*)?/>(.*)',$s,$Atmp1) or
            
ereg('<([^<>/ ]*)( [^<>]*)?>(.*)',$s,$Atmp1) and
            
$Atmp2=explode('</'.$Atmp1[1].'>',$Atmp1[3],2);++$c) {
    
$E=array();
    
$tag=$Atmp1[1];
    if (
$Atmp1[2]) {
      
$Atmp3=explode(' ',substr($Atmp1[2],1));
      foreach (
$Atmp3 as $d) {
        
$Atmp4=explode('=',$d,2);
        
$Atmp4[1]=ereg_replace('^"(.*)"$','\1',$Atmp4[1]);
        
$E[$Atmp4[0]]=$Atmp4[1];
      }
    }
    if (
$Atmp2) {
      if (!
xml2array_sub($E,$Atmp2[0])) {
        
$E=$Atmp2[0];
      }
      
$s=$Atmp2[1];               //rest of the xml-code
      
$Atmp2=false;
    }
    else {
      
$s=$Atmp1[3];               //rest of the xml-code
    
}
    if (isset(
$A[$tag])) {                        //does it already exist? 20040715: isset() added
      
if (!is_array($A[$tag]) or !$A[$tag][0]) {  //not already a numberically indexed array?
        
$Atag=$A[$tag];                           //remove element again
        
unset($A[$tag]);
        
$A[$tag][]=$Atag;                         //make old element first element of it's former self
      
}
      if (
$E) {
        
$A[$tag][]=$E;            //add new element
      
}
    }
    else {
      if (
$E) {
        
$A[$tag]=$E;                           //put it in the array under it's tag name
        
if ($tag=='ErrorMsg'$error_msg=$E;  //make this a global error message, because it can be anywhere in the XML code
      
}
    }
  }
  return 
$c;
}

//end