static function changeName($elem, $name) { $dom_sxe = dom_import_simplexml($elem); $dom = new DOMDocument('1.0', "UTF-8"); $dom->ecoding = "UTF-8"; $node = $dom->importNode($dom_sxe, true); $node = $dom->appendChild($node); $newnode = $dom->createElement($name); foreach ($node->childNodes as $child) { $child2 = $child->cloneNode(true); $newnode->appendChild($child2); unset($child2); } foreach ($node->attributes as $attrName => $attrNode) { $newnode->setAttribute($attrName, $attrNode->nodeValue); } //"//*[starts-with(name(),'B')]" $res = t(new DOMXPath($dom))->evaluate("//*[starts-with(name(),'W')]"); if (!$res instanceof DOMNodeList || $res instanceof DOMNodeList && $res->length == 0) { $newnode->setAttribute("__use_cdata", "1"); } $dom->replaceChild($newnode, $node); unset($dom_sxe); unset($node); unset($newnode); return simplexml_import_dom($dom); }
private function _repopulate_form($content) { $DOM = new DOMDocument(); @$DOM->loadHTML($content); $Xpath = new DOMXPath($DOM); // Remove <!DOCTYPE $DOM->removeChild($DOM->firstChild); // Remove <html><body></body></html> $DOM->replaceChild($DOM->firstChild->firstChild->firstChild, $DOM->firstChild); // Repopulate Text and Password Inputs $inputs = $Xpath->query('//input[@type="text"] | //input[@type="password"]'); foreach ($inputs as $Input) { if ($name = $Input->getAttribute('name')) { $Input->setAttribute('value', $this->input->post($name)); } } // Repopulate Radio and Checkbox Inputs $inputs = $Xpath->query('//input[@type="radio"] | //input[@type="checkbox"]'); foreach ($inputs as $Input) { if ($name = $Input->getAttribute('name')) { $value = $Input->getAttribute('value'); if ($this->input->post($name) == $value) { $Input->setAttribute('checked', 'checked'); } } } // Repopulate Textareas $textareas = $Xpath->query('//textarea'); foreach ($textareas as $Textarea) { if ($name = $Textarea->getAttribute('name')) { $Textarea->nodeValue = $this->input->post($name); } } // Repopulate Dropdowns $options = $Xpath->query('//select/option'); foreach ($options as $Option) { if ($name = $Option->parentNode->getAttribute('name')) { $value = $Option->getAttribute('value'); if ($this->input->post($name) == $value) { $Option->setAttribute('selected', 'selected'); } } } return $DOM->saveHTML(); }
static function fixChildrenClass($content, $elementType, $class, $fixRawHtml = true) { $classPath = '\\AbstractElement\\' . $elementType; // is this an object that extends AbstractElement? if (is_a($content, '\\Element')) { // is this of the right element type? if (is_a($content, $classPath)) { $content->addClass($class); } if (isset($content->contents)) { foreach ($content->contents as $index => $value) { $content->contents[$index] = AbstractElement\Helper::fixChildrenClass($value, $elementType, $class); } } return $content; } if (is_string($content) && $fixRawHtml) { $dom = new \DOMDocument(); $dom->loadHtml($content); $reflectionClass = new \ReflectionClass($classPath); $elements = $dom->getElementsByTagName($reflectionClass->getConstant('tag')); foreach ($elements as $element) { $element->setAttribute('class', $element->getAttribute('class') . ' ' . $class); } $dom->removeChild($dom->doctype); $dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild); return $dom->saveHTML(); } }
/** * Adds new child at the end of the children. * @param \DOMNode $newNode The appended child. * @param boolean $unique If sets TRUE, search if exists the same node. * @return \DOMNode The node added or if is unique, returns the node found. */ public function appendChild(\DOMNode $newNode, $unique = false) { if ($unique) { $node = parent::getElementsByTagName($newNode->localName)->item(0); } if ($node !== null) { $newNode = parent::replaceChild($newNode, $node); } else { $newNode = parent::appendChild($newNode); } return $newNode; }
/** * @param string $item * @param int $key * @return string */ public function extProc_beforeAllWrap($item, $key) { if (!empty($item)) { $pageId = $this->I['uid']; $dom = new \DOMDocument(); $dom->loadHTML(mb_convert_encoding($item, 'HTML-ENTITIES', 'UTF-8')); $link = $dom->getElementsByTagName('a'); $item = $link->item(0); $dataAttribute = 'bwrk_onepage_' . $pageId; $classAttribute = $dom->createAttribute('data-bwrkonepage-id'); $classAttribute->value = $dataAttribute; $item->appendChild($classAttribute); $dom->removeChild($dom->doctype); $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); $newItem = $dom->saveHTML(); return $newItem; } }
/** * Append product recommendations to Autocomplete block html * * @param string $html * @return string */ protected function _appendTopRecommendations($html) { $recommendationsModel = Mage::getModel('autocompleterecommendations/recommendation'); $query = Mage::helper('catalogsearch')->getQuery(); $productRecommendationsHtml = $recommendationsModel->getProductRecommendationsHtml($query); if ($productRecommendationsHtml) { $dom = new DOMDocument('1.0', 'utf8'); $dom->loadHTML($html); $uls = $dom->getElementsByTagName('ul'); $ul = $uls->item(0); $productRecommendationsDom = $recommendationsModel->getRecommendationsDom($productRecommendationsHtml); $productRecommendationsDom = $dom->importNode($productRecommendationsDom, true); $ul->appendChild($productRecommendationsDom); $dom->removeChild($dom->doctype); $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); $html = $dom->saveHTML(); } return $html; }
function fof_item_targets($content) { /* quiet warnings */ $old_xml_err = libxml_use_internal_errors(true); $dom = new DOMDocument(); /* Load content into DOM, within a div wrapper. Wrapper div will be stripped before returning altered content. Without doing this, any bare text content would get wrapped in p elements while being parsed in. */ $dom->loadHtml('<div>' . mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8") . '</div>'); /* strip <!DOCTYPE> which DOMDocument adds */ $dom->removeChild($dom->firstChild); /* strip <html><body> which DOMDocument adds */ $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); /* replace or add link targets */ $xpath = new DOMXpath($dom); foreach ($xpath->query('//a') as $node) { $node->setAttribute('target', '_blank'); } $content_out = ''; /* emit the updated contents inside our div */ /* start at the first node inside first div.. */ $node = $dom->firstChild->firstChild; while ($node) { $content_out .= $dom->saveHTML($node); /* repeat for all nodes at this level */ $node = $node->nextSibling; } foreach (libxml_get_errors() as $error) { /* just ignore warnings */ if ($error->level === LIBXML_ERR_WARNING) { continue; } fof_log(__FUNCTION__ . ': ' . $error->message); } libxml_clear_errors(); libxml_use_internal_errors($old_xml_err); return $content_out; }
public function create($replaceHtml = false) { $this->_html = file_get_contents($this->getViewFile()); // this is relative root directory $dom = new \DOMDocument(); // libxml_use_internal_errors(true); $dom->loadHTML($this->_html); // libxml_clear_errors(); if ($replaceHtml) { // use this if we ever need to get rid of doc types or html tags that we for some reason get wrapped in when calling loadHTML // remove doc type $dom->removeChild($dom->firstChild); // remove <html><body></body></html> $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); } foreach ($this->getViewElements() as $viewElement) { $viewElement->replaceHtml($dom, $this->getViewElementValue()); } $html = $dom->saveHTML(); return $this->_html = trim($html); }
protected function processTag($elementMarkup) { # http://stackoverflow.com/q/1148928/200145 libxml_use_internal_errors(true); $DOMDocument = new DOMDocument(); # http://stackoverflow.com/q/11309194/200145 $elementMarkup = mb_convert_encoding($elementMarkup, 'HTML-ENTITIES', 'UTF-8'); # http://stackoverflow.com/q/4879946/200145 $DOMDocument->loadHTML($elementMarkup); $DOMDocument->removeChild($DOMDocument->doctype); $DOMDocument->replaceChild($DOMDocument->firstChild->firstChild->firstChild, $DOMDocument->firstChild); $elementText = ''; if ($DOMDocument->documentElement->getAttribute('markdown') === '1') { foreach ($DOMDocument->documentElement->childNodes as $Node) { $elementText .= $DOMDocument->saveHTML($Node); } $DOMDocument->documentElement->removeAttribute('markdown'); $elementText = "\n" . $this->text($elementText) . "\n"; } else { foreach ($DOMDocument->documentElement->childNodes as $Node) { $nodeMarkup = $DOMDocument->saveHTML($Node); if ($Node instanceof DOMElement and !in_array($Node->nodeName, $this->textLevelElements)) { $elementText .= $this->processTag($nodeMarkup); } else { $elementText .= $nodeMarkup; } } } # because we don't want for markup to get encoded $DOMDocument->documentElement->nodeValue = 'placeholder'; $markup = $DOMDocument->saveHTML($DOMDocument->documentElement); $markup = str_replace('placeholder', $elementText, $markup); return $markup; }
/** * Removes dom nodes, eg: <script> elements * * @param $html * @param $xpathString * @return string */ private function removeDomNodes($html, $xpathString) { $dom = new DOMDocument(); // Libxml constants not available on all servers (Libxml < 2.7.8) // $html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $dom->loadHtml('<div class="form-group">' . $html . '</div>'); # remove <!DOCTYPE $dom->removeChild($dom->doctype); # remove <html><body></body></html> $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); // remove the required node $xpath = new DOMXPath($dom); while ($node = $xpath->query($xpathString)->item(0)) { $node->parentNode->removeChild($node); } return $dom->saveHTML(); }
private function parse($content) { $extension = $this->getExtension(); $path = $this->getPath(); $parseVariable = $this->isParseVariable(); $options = $this->getOptions(); /* * Everything inside a <% IGNORE %>...<% IGNOER_END %> block * will be ignored from being parsed */ $ignoreBlock = array(); $content = preg_replace_callback('@(<% *IGNORE *%>(.*?)<% *IGNORE_END *%>)@s', function ($matches) use(&$ignoreBlock) { $ignoreBlock[] = $matches[2]; return '<!--SimPHPfyIgnoreBlock#' . count($ignoreBlock) . '#SimPHPfyIgnoreBlock-->'; }, $content); /* * Code block is in the form <% code %>, code can be any valid * PHP statements. * A special form of code block is <%= ${variable_name} %> * which is equivalent to echo a variable * * Every code snippet is stored inside the $codeBlock Array to * prevent variable parsing from corrupting the whole document */ $codeBlock = array(); $content = preg_replace_callback('@(<%= *(.*?[^\\\\]) *%>)@s', function ($matches) use(&$codeBlock) { $codeSnippet = $matches[2]; if (preg_match('@^\\${([a-zA-Z_\\x7f-\\xff][\\[\\]\'"a-zA-Z0-9_\\x7f-\\xff*]*(\\[[\'"][a-zA-Z0-9_\\x7f-\\xff*]*[\'"]\\])*)}$@', $codeSnippet)) { $codeSnippet = "<?php if (isset({$codeSnippet})) { echo {$codeSnippet}; } ?>"; } elseif (preg_match('@^\\$([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff*]*(\\[[\'"][a-zA-Z0-9_\\x7f-\\xff*]*[\'"]\\])*)$@', $codeSnippet)) { $codeSnippet = "<?php if (isset({$codeSnippet})) { echo {$codeSnippet}; } ?>"; } $codeBlock[] = $codeSnippet; return '<!--SimPHPfyCodeBlock#' . count($codeBlock) . '#SimPHPfyCodeBlock-->'; }, $content); $content = preg_replace_callback('@(<% *(.*?[^\\\\]) *%>)@s', function ($matches) use(&$codeBlock, $path) { $codeSnippet = $matches[2]; if ($codeSnippet == 'IGNORE_MINIFY' || $codeSnippet == 'IGNORE_MINIFY_END') { return $matches[0]; } elseif (preg_match('@^render.*$@', $codeSnippet)) { /* * Layout rendering */ $codeSnippet = '<' . $codeSnippet . ' />'; $dom = new DOMDocument(); @$dom->loadXML($codeSnippet); /* * extract the attributes of render tag */ $render = $dom->getElementsByTagName('render')->item(0); // <% render file='header.html' directory='' static='' dynamic='' %> $file = $directory = $dynamic = $format = $parsedDirectory = ''; if (($file = $render->getAttribute('file')) == '') { throw new InvalidTemplateException(array($path, 'Missing `file` for layout rendering')); } $directory = ASSERT; $parsedDirectory = TEMP_VIEW . 'Assert' . DS; if ($dirAttr = $render->getAttribute('directory') != '') { $directory .= $dirAttr . DS; $parsedDirectory = TEMP_VIEW . $dirAttr . DS; } /* * If `controller` attribute is spceified, the layout is * inside the View/:Controller */ if (($controllerAttr = $render->getAttribute('controller')) != '') { $directory = VIEW . $controllerAttr . DS; $parsedDirectory = TEMP_VIEW . $controllerAttr . DS; } if (($staticAttr = $render->getAttribute('static')) != '') { $dynamic = !$staticAttr; } /* * `dynamic` attribute always overwrite `static` attribute, * thought it is not recommended to set both attributes */ if (($dynamicAttr = $render->getAttribute('dynamic')) != '') { $dynamic = $dynamicAttr; } /* * The behaviour of render. When a render code is parsed, * should it return a URL to the rendered file or directly * render that file, possiblities: 'url' | 'direct' * default: 'direct' */ if (($behaviourAttr = $render->getAttribute('behaviour')) == '') { $behaviour = 'direct'; } else { $behaviour = $behaviourAttr; } $format = $render->getAttribute('format'); $optionArray = 'array('; $i = 0; if ($format != '') { $optionArray .= "'format' => {$format}"; $i++; } if ($parsedDirectory != '') { $optionArray .= ($i++ == 0 ? '' : ', ') . "'parsedDirectory' => '{$parsedDirectory}'"; } if ($dynamic !== '') { $optionArray .= ($i++ == 0 ? '' : ', ') . '\'dynamic\' => ' . ($dynamic ? 'TRUE' : 'FALSE'); } else { $dynamic = TRUE; } $optionArray .= ')'; $extension = substr(strrchr($file, "."), 1); if ($behaviour == 'direct' || $dynamic) { if ($extension == 'html') { $codeSnippet = "<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>"; } elseif ($extension == 'js') { $codeSnippet = "<script><?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?></script>"; } elseif ($extension == 'css') { $codeSnippet = "<style><?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?></style>"; } } else { if ($extension == 'html') { $codeSnippet = "<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>"; } else { $optionArray = substr($optionArray, 0, -1) . ($i++ == 0 ? '' : ', ') . '\'relative\' => TRUE)'; if ($extension == 'js') { $codeSnippet = "<script src=\"<?php echo Template::render('{$file}', '{$directory}', {$optionArray}); ?>\"></script>"; } elseif ($extension == 'css') { $codeSnippet = "<link rel=\"stylesheet\" href=\"<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>\" />"; } } } } else { $codeSnippet = '<?php ' . str_replace('\\%>', '%>', $codeSnippet) . ' ?>'; } $codeBlock[] = $codeSnippet; return '<!--SimPHPfyCodeBlock#' . count($codeBlock) . '#SimPHPfyCodeBlock-->'; }, $content); /* * Perform HTML specificied parsing */ if ($extension == 'html') { $htmlBlock = array(); /* * gurantee the form tag is not inside a comment by examining the * DOM Tree instead of pure regular expression */ $dom = new DOMDocument(); @$dom->loadHTML($content); $forms = $dom->getElementsByTagName('form'); for ($i = 0; $i < $forms->length; $i++) { /* * Re-create the DOM because the previous iteration have * changed the content of $content */ $dom = new DOMDocument(); @$dom->loadHTML($content); $form = $dom->getElementsByTagName('form')->item($i); if ($form->textContent == '') { /* * Create dummy block to make the form tag recognizable */ $dummyString = '<!--SimPHPfyDummyBlock#' . $i . '#SimPHPfyDummyBlock-->'; $textNode = $dom->createTextNode($dummyString); $form->appendChild($textNode); $content = $dom->saveHTML(); $pattern = '@(< *form.*?>)(' . $dummyString . ')@'; } else { /* * Save the form HTML content into the $htmlBlock */ $htmlContent = ''; while ($form->hasChildNodes()) { /* * Loop through the child to skip the parent form tag * from including into the stored $htmlBlock */ $node = $form->childNodes->item(0); $htmlContent .= $dom->saveXML($node); $form->removeChild($node); } $htmlBlock[] = $htmlContent; $commentNode = $dom->createComment('SimPHPfyHTMLBlock#' . count($htmlBlock) . '#SimPHPfyHTMLBlock'); $htmlBlockString = '<!--SimPHPfyHTMLBlock#' . count($htmlBlock) . '#SimPHPfyHTMLBlock-->'; $form->appendChild($commentNode); $content = $dom->saveHTML(); $pattern = '@(< *form.*?>)(' . $htmlBlockString . ')@'; } $content = preg_replace_callback($pattern, function ($matches) use($options, $path) { $formDom = new DOMDocument(); @$formDom->loadHTML($matches[1]); $formTags = @$formDom->getElementsByTagName('form'); $formTag = $formTags->item(0); $controller = $action = ''; /* * data-controller and data-action attributes determine which * controller and action the form should send to * * A table of the possible values of data-* are as followed: * data-controller data-action result * String String $contoller/$action * Omitted String :Controller/$action * String Omitted Disallowed * Omitted Omitted :Controller/:Action */ if ($formTag->getAttribute('data-helper') == 'simphpfy') { if ($formTag->getAttribute('data-controller') == '') { if ($formTag->getAttribute('data-action') == '') { if (isset($options['controller'])) { $controller = $options['controller']->getController(); $action = $options['controller']->getAction(); } else { throw new InvalidTemplateException(array($path, 'missing controller and/or action for form helper')); } } else { if (isset($options['controller'])) { $controller = $options['controller']->getController(); $action = $formTag->getAttribute('data-action'); } else { throw new InvalidTemplateException(array($path, 'missing controller for form helper')); } } } else { if ($formTag->getAttribute('data-action') == '') { throw new InvalidTemplateException(array($path, 'malformed form helper')); } else { $controller = $formTag->getAttribute('data-controller'); $action = $formTag->getAttribute('data-action'); } } if ($controller && $action) { $actionAttr = DIRECTORY_PREFIX . $controller . DS . $action; if (($id = $formTag->getAttribute('data-id')) != '') { $actionAttr .= DS . $id; } $formTag->setAttribute('action', $actionAttr); } else { throw new InvalidTemplateException(array($path, 'malformed form helper')); } // check if method is PUT or DELETE if ($formTag->getAttribute('data-method') != '') { $method = strtoupper($formTag->getAttribute('data-method')); if ($method == "PUT" || $method == "DELETE") { $formTag->setAttribute('method', 'POST'); } elseif ($method == 'GET' || $method == 'POST') { $formTag->setAttribute('method', $method); } $inputMethod = $formDom->createElement('input'); $inputMethod->setAttribute('type', 'hidden'); $inputMethod->setAttribute('name', '_method'); $inputMethod->setAttribute('value', $method); $formTag->appendChild($inputMethod); } // remove <!DOCTYPE $formDom->removeChild($formDom->doctype); // remove <html><body></body></html> $formDom->replaceChild($formDom->firstChild->firstChild->firstChild, $formDom->firstChild); return str_replace('</form>', '', $formDom->saveHTML()) . $matches[2]; } else { return $matches[0]; } }, $content); } $content = preg_replace_callback('@<!--SimPHPfyHTMLBlock#([0-9]+)#SimPHPfyHTMLBlock-->@', function ($matches) use($htmlBlock) { return $htmlBlock[(int) $matches[1] - 1]; }, $content); $dom = new DOMDocument(); @$dom->loadHTML($content); $this->parseInput($dom->getElementsByTagName('input'), $codeBlock); $this->parseInput($dom->getElementsByTagName('select'), $codeBlock); $this->parseInput($dom->getElementsByTagName('textarea'), $codeBlock); $content = $dom->saveHTML(); } if ($parseVariable) { $content = preg_replace('@([^\\\\]|]^)\\${([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)}\\$@', '<?php echo $\\2; ?>', $content); $content = preg_replace('@([^\\\\]|^)\\$([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\\$@', '<?php echo $\\2; ?>', $content); } $content = preg_replace_callback('@<!--SimPHPfyIgnoreBlock#([0-9]+)#SimPHPfyIgnoreBlock-->@', function ($matches) use($ignoreBlock) { return $ignoreBlock[(int) $matches[1] - 1]; }, $content); $content = preg_replace_callback('@<!--SimPHPfyCodeBlock#([0-9]+)#SimPHPfyCodeBlock-->@', function ($matches) use($codeBlock) { return $codeBlock[(int) $matches[1] - 1]; }, $content); $content = preg_replace('@<!--SimPHPfyDummyBlock#([0-9]+)#SimPHPfyDummyBlock-->@', '', $content); return $content; }
public static function tidyHTML($html, $useDOM = false) { if (!$html) { return $html; } if (!$useDOM) { if (!self::$_htmlFixer) { self::$_htmlFixer = new BBM_Helper_HtmlFixer(); } $htmlFixer = self::$_htmlFixer; return $htmlFixer->getFixedHtml($html); } $doc = new DOMDocument(); libxml_use_internal_errors(true); $readyContent = self::_beforeLoadHtml($html); $doc->loadHTML('<?xml encoding="utf-8"?>' . $readyContent); libxml_clear_errors(); $doc->encoding = 'utf-8'; $doc->formatOutput = true; $doc->removeChild($doc->firstChild); //remove html tag $doc->removeChild($doc->firstChild); //remove xml fix $doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild); //make wip tag content as first child $html = $doc->saveHTML($doc->documentElement); $html = self::_afterSaveHtml($html); return $html; }
/** * Method which converts all relative "href" and "src" URLs of * a HTML snippet with their absolute equivalent * @param string $xmlString a HTML snippet as string with the relative URLs to be replaced * @param string $absoluteUrl the approptiate absolute url of the HTML snippet * @return string the result HTML snippet as a string */ protected function substituteRelativeLinks($xmlString, $absoluteUrl) { $dom = new \DOMDocument(); $dom->preserveWhiteSpace = false; // return, if xml is empty or loading the HTML fails if (trim($xmlString) == "" || !@$dom->loadHTML($xmlString)) { return $xmlString; } // remove <!DOCTYPE $dom->removeChild($dom->firstChild); // remove <html></html> $dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild); $substitution = array("href", "src"); foreach ($substitution as $attribute) { $xpath = new \DOMXpath($dom); $xpathResult = $xpath->query("//*[@" . $attribute . " " . "and not(contains(@" . $attribute . ", '://')) " . "and not(starts-with(@" . $attribute . ", 'mailto:'))]"); foreach ($xpathResult as $linkNode) { $urlElement = $linkNode->attributes->getNamedItem($attribute); $abs = $this->relativeToAbsoluteUrl($urlElement->nodeValue, $absoluteUrl); $urlElement->nodeValue = htmlspecialchars($abs); } } // save dom to string and remove <body></body> $xmlString = substr(trim($dom->saveHTML()), 6, -7); // domdocument spoils the string with line breaks between the elements. strip them. $xmlString = str_replace("\n", "", $xmlString); return $xmlString; }
<?php if (isset($_POST['description'], $_POST['leccion'], $_POST['resultado'], $_POST['bloques'], $_POST['curso'], $_POST['momento'], $_POST['idFinal'])) { $des = str_replace("<", "<", $_POST['description']); $des1 = str_replace(">", ">", $des); $nombre = "../../courses/" . $_POST['leccion'] . "/" . $_POST['leccion'] . ".txt"; $dom = new DOMDocument(); $dom->loadHTML($_POST['bloques']); $dom->removeChild($dom->doctype); $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); foreach ($dom->getElementsByTagName('div') as $item) { //substr($dom->saveXML($dom->getElementsByTagName('div')->item(0)), 5, -6) $item->setAttribute('id', 'TTT'); $convertedHTML = $dom->saveHTML(); } $data = $_POST['momento'] . "^^^" . $des1 . "^^^" . $convertedHTML . "^^^" . $_POST['resultado'] . "^^^" . $_POST['idFinal'] . "\$\$\$"; file_put_contents($nombre, $data, FILE_APPEND | LOCK_EX); }
public function wrapOptionsInOptGroups($html) { $dom = new DOMDocument(); @$dom->loadHTML($html); $xpathObj = new DOMXPath($dom); $select = $dom->getElementsByTagName('select')->item(0); foreach ($this->_groups as $groupName => $groupData) { if (count($groupData['items']) == 0) { continue; } $optgroup = $dom->createElement('optgroup'); $optgroup->setAttribute('label', $groupData['label']); foreach ($groupData['items'] as $itemId) { $option = $xpathObj->query("//select/option[@value='{$itemId}']", $select)->item(0); $option = $select->removeChild($option); $optgroup->appendChild($option); } $select->appendChild($optgroup); } // Moving remaining options in end of list foreach ($xpathObj->query('//select/option', $select) as $option) { if (empty($option->nodeValue)) { continue; } try { $option = $select->removeChild($option); $select->appendChild($option); } catch (DOMException $e) { } } // Removing doctype, html, body $dom->removeChild($dom->doctype); $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild); return $dom->saveHTML(); }
/** * Load HTTPd configuration from a string. * * @param string $contents Contents of the configuration. * @param string $filename */ public function loadConfiguration($contents, $filename = null) { $of_file = isset($filename) ? " of {$filename}" : null; // Remove existing document parent::replaceChild($this->createSection('_'), $this->documentElement); // Parse $sets = array(); if (!preg_match_all('%^(?P<indent>[ \\t]*+)(?:(?P<comment>#(?:[^\\r\\n\\\\]++|\\\\\\r?\\n?)++)|<[ \\t]*(?P<section>\\w++)(?P<section_args>(?:\\\\\\r?\\n|[ \\t]++)(?:[^>\'"\\r\\n\\\\]++|"(?:[^"\\\\]++|\\\\.)*+"|\'(?:[^\'\\\\]++|\\\\.)*+\'|\\\\\\r?\\n?)++)>[ \\t]*|</(?P<end_section>\\w++)>[ \\t]*|(?P<directive>\\w++)(?P<directive_args>(?:[ \\t]++|\\\\\\r?\\n)(?:[^\\r\\n\\\\]++|\\\\\\r?\\n?)++)|(?P<syntaxerr>\\S[^\\n]*))(?P<blank>\\r?\\n\\s*)*$%ms', $contents, $sets, PREG_SET_ORDER)) { return; } $matches = null; $lineno = preg_match('/^([ \\t\\r]*\\n)*/', $contents, $matches) ? substr_count($matches[0], "\n") : 0; unset($contents); // Create document if (isset($filename)) { $this->documentURI = $filename; } $section = $this->documentElement; $set = null; foreach ($sets as &$set) { $lineno++; $extra_lines = 0; if (!empty($set['indent'])) { $section->appendChild($this->createTextNode($set['indent'])); } if (!empty($set['directive'])) { $node = $section->appendChild($this->createDirective($set['directive'])); if (!empty($set['directive_args'])) { $this->parseArguments($node, $set['directive_args']); $extra_lines = substr_count($set['directive_args'], "\n"); } } elseif (!empty($set['section'])) { $node = $section->appendChild($this->createSection($set['section'])); if (!empty($set['section_args'])) { $this->parseArguments($node, $set['section_args']); $extra_lines = substr_count($set['section_args'], "\n"); } $section = $node; } elseif (!empty($set['end_section'])) { if ($section->nodeName != $set['end_section']) { if ($section === $this->firstChild) { throw new \DOMException("Syntax error on line {$lineno}{$of_file}: </{$set['end_section']}> without matching <{$set['end_section']}> section", DOM_SYNTAX_ERR); } else { throw new \DOMException("Syntax error on line {$lineno}{$of_file}: Expected </{$section->nodeName}> but saw </{$set['end_section']}>", DOM_SYNTAX_ERR); } } $section = $section->parentNode; } elseif (!empty($set['comment'])) { $node = $section->appendChild($this->createComment(str_replace("\\\n", "\n", substr($set['comment'], 1), $extra_lines))); } elseif (!empty($set['syntaxerr'])) { throw new \DOMException("Syntax error on line {$lineno}{$of_file}: Invalid command '{$set['syntaxerr']}'.", DOM_SYNTAX_ERR); } /*if (isset($node)) { $node->uriDocument = $filename; $node->_lineno = $lineno; }*/ if (!empty($set['blank'])) { $section->appendChild($this->createTextNode(preg_replace('/^\\r?\\n(.*)$/', "\$1\n", $set['blank']))); } $lineno += $extra_lines + (!empty($set['blank']) ? substr_count($set['blank'], "\n") : 0); unset($node); } if ($section !== $this->firstChild) { throw new \DOMException("Syntax error: <{$section->nodeName}> was not closed.", DOM_SYNTAX_ERR); } }