/** * Convert xml node to array or string * * @param \DOMDocument $node * @return array|string */ public function convert($node) { $result = []; if ($node->nodeType == XML_TEXT_NODE) { $result = $node->nodeValue; } else { if ($node->hasChildNodes()) { $children = $node->childNodes; for ($i = 0; $i < $children->length; $i++) { $child = $children->item($i); if ($child->nodeName != '#text') { $result[$child->nodeName][] = $this->convert($child); } else { if ($child->nodeName == '#text') { $text = $this->convert($child); if (trim($text) != '') { $result[$child->nodeName] = $this->convert($child); } } } } } if ($node->hasAttributes()) { $attributes = $node->attributes; if (!is_null($attributes)) { foreach ($attributes as $attribute) { $result[$attribute->name] = $attribute->value; } } } } return $result; }
/** * Convert opml xml node into array for import * http://www.php.net/manual/en/class.domdocument.php#101014 * * @param DOMDocument $node Node to convert into array * * @return array Array corresponding to the given node */ public static function getArrayFromXml($node) { $array = false; if ($node->hasAttributes()) { foreach ($node->attributes as $attr) { $array[$attr->nodeName] = $attr->nodeValue; } } if ($node->hasChildNodes()) { if ($node->childNodes->length == 1) { $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue; } else { foreach ($node->childNodes as $childNode) { if ($childNode->nodeType != XML_TEXT_NODE) { $array[$childNode->nodeName][] = Opml::getArrayFromXml($childNode); } } } } return $array; }
/** * @param \DOMDocument|string $xml $xml * @return array */ public function convertXMLToArray($xml) { $result = array(); if ($xml->hasAttributes()) { $attrs = $xml->attributes; foreach ($attrs as $attr) { $result['@attributes'][$attr->name] = $attr->value; } } if ($xml->hasChildNodes()) { $children = $xml->childNodes; if ($children->length == 1) { $child = $children->item(0); if ($child->nodeType == XML_TEXT_NODE || $child->nodeType == XML_CDATA_SECTION_NODE) { $result['_value'] = $child->nodeValue; return count($result) == 1 ? $result['_value'] : $result; } } $groups = array(); foreach ($children as $child) { if (!isset($result[$child->nodeName])) { $result[$child->nodeName] = $this->convertXMLToArray($child); } else { if (!isset($groups[$child->nodeName])) { $result[$child->nodeName] = array($result[$child->nodeName]); $groups[$child->nodeName] = 1; } $result[$child->nodeName][] = $this->convertXMLToArray($child); } if (empty($result[$child->nodeName])) { unset($result[$child->nodeName]); } elseif (is_array($result[$child->nodeName])) { $values = array(); foreach ($result[$child->nodeName] as $key => $val) { if (!empty($result[$child->nodeName][$key])) { $values[] = $result[$child->nodeName][$key]; if (count($values) > 1) { break; } } } if (empty($values)) { unset($result[$child->nodeName]); } } } } return $result; }