/** * @param $newData * @return DOMDocument * @throws Exception */ private static function makeDomFromNewData($newData) { $newXmlString = Dfi_Xml::castToXmlString($newData); $newXml = Dfi_Xml::asSimpleXml($newXmlString); $x = Dfi_Xml::asSimpleXml('<current></current>'); /** @var SimpleXMLElement $value */ foreach ($newXml as $key => $value) { if ((string) $value != '') { $x->addChild($key, $value); } } $newXml = $x; //new DOM document definition $dom = new DOMDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = FALSE; $dom->encoding = 'UTF-8'; $newDataDom = dom_import_simplexml($newXml); $currentDom = $dom->createElement('data'); $dom->appendChild($currentDom); $newDataImported = $dom->importNode($newDataDom, true); $currentDom->appendChild($newDataImported); $x = $dom->saveXML($dom); return $dom; }
/** * @param SimpleXMLElement $xml * @param $xpathQuery * @param $value * @param bool $returnAsString * @return object|SimpleXMLElement|string * @throws Exception */ public function setDataByXpath(SimpleXMLElement $xml, $xpathQuery, $value, $returnAsString = false) { if ($value) { if (!$xml) { $xml = simplexml_load_string(Dfi_Xml::from_array(array())); } $elements = $xml->xpath($xpathQuery); if ($elements && count($elements) > 0) { if (count($elements) > 1) { throw new Exception('multiple elements found dont know which update'); } else { $element = $elements[0]; /* @var $element SimpleXMLElement */ $val = (string) $element; if ($value != $val) { dom_import_simplexml($element)->nodeValue = $value; } } } else { $parts = explode('/', $xpathQuery); $last = array_pop($parts); $xml->{$last} = $value; } if ($returnAsString) { return self::checkIsValidXmlStirng($xml->asXML()); } } return $xml; }