XML stuff
Fri Mar 09, 2007 · 165 words

A (weird) way to convert PHP arrays to XML. I came up with this for Collective - passing media metadata (with getid3) from the server to JavaScript. It's not supposed to work with numeric indexes - the algorithm doesn't break, it just produces invalid XML (can't have numbers as element names):

    function array2xml($array)
    {
      foreach ($array as $k => $v) {
        if (is_array($v)) {
          $out .= "<$k " . array2xml($v) . "</$k>\n";
        }
        else {
          $out .= "\n\t$k='$v'";
          if (is_array(next($array)) || (array_pop(array_keys($array)) == $k))
            $out .= ">\n";
            }
        }
      return $out;
    }

A way to convert a file system hierarchy into an XML document, in Python. This is for a simple file-cataloguer I desperately needed (more on this later, hopefully):

    imp = minidom.getDOMImplementation()
    ldoc = imp.createDocument(None, 'Library', None)

    def parsedir(dirname, parent = ldoc.documentElement):

      global ldoc

      if os.path.isdir(dirname):
        newDir = ldoc.createElement('Directory')
        newDir.setAttribute('path', dirname)
        parent.appendChild(newDir)
        parent = newDir

        for i in os.listdir(dirname):
          fp = os.path.join(dirname, i)
          if os.path.isdir(fp):
            parsedir(fp, newDir)

          else:
            newFile = ldoc.createElement('File')
            newFile.setAttribute('name', i)
            parent.appendChild(newFile)

back · essays · credits ·