/** * takes a file name of an xml document and returns an json representation * * @param string $fileName */ function convert($fileName) { $d = new DOMDocument(1, "UTF-8"); $d->load($fileName); $ret[$d->documentElement->nodeName] = dom_to_array($d->documentElement); return json_encode($ret); }
/** * Transform DOM object to an array */ function dom_to_array($node, $parent_name = NULL) { $name = $node->nodeName; $metadata = array(); // copy attributes foreach ($node->attributes as $attr) { $metadata['@' . $attr->name] = $attr->value; } // process children foreach ($node->childNodes as $child) { // process children elements if ($child->nodeType == XML_ELEMENT_NODE) { if ($node->childNodes->length == 1) { $metadata[$child->nodeName] = dom_to_array($child, $name); } else { $metadata[$child->nodeName][] = dom_to_array($child, $name); } } elseif ($child->nodeType == XML_TEXT_NODE) { $value = trim($child->nodeValue); if (!empty($value)) { $metadata['#value'] = str_replace("\n", ' ', $value); } } } if ($parent_name !== NULL) { if (count($metadata) == 1 && isset($metadata['#value'])) { $metadata = $metadata['#value']; } } return $metadata; }