/** * This test functions shows an example of SmartDOMDocument in action. * A sample HTML fragment is loaded. * Then, the first image in the document is cut out and saved separately. * It also shows that Russian characters are parsed correctly. * */ public static function testHTML() { $content = <<<CONTENT <div class='class1'> <img src='http://www.google.com/favicon.ico' /> Some Text <p>русский</p> </div> CONTENT; print "Before removing the image, the content is: \n" . htmlspecialchars($content) . "<br>\n"; $content_doc = new SmartDOMDocument(); $content_doc->loadHTML($content); try { $first_image = $content_doc->getElementsByTagName("img")->item(0); if ($first_image) { $first_image->parentNode->removeChild($first_image); $content = $content_doc->saveHTMLExact(); $image_doc = new SmartDOMDocument(); $image_doc->appendChild($image_doc->importNode($first_image, true)); $image = $image_doc->saveHTMLExact(); } } catch (Exception $e) { } print "After removing the image, the content is: \n" . htmlspecialchars($content) . "<br>\n"; print "The image is: \n" . htmlspecialchars($image); }
/** * Get's the content that's about to be output * and fixes the images to follow the responsive.io service conventions. * @param string $content the unmodified html * @return string the modified html */ public function update_images($content) { require_once plugin_dir_path(__FILE__) . 'includes/SmartDOMDocument.class.php'; // Create a DOMDocument instance $dom = new SmartDOMDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; if (empty($content)) { return; } // Loads our content as HTML @$dom->loadHTML($content); // Get all of our img tags $images = $dom->getElementsByTagName('img'); // Loop through all the images in this content foreach ($images as $image) { // Get some attributes $src = $image->getAttribute('src'); $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION)); $alt = $image->getAttribute('alt'); // Only interested in those who have a src set // and that are not gifs if (empty($src) || strpos($ext, 'gif') !== false) { continue; } // Create our fallback image before changing this node $imageClone = $image->cloneNode(); // Add the src as a data-src attribute instead $image->setAttribute('data-src', $src); // Empty the src of this img $image->setAttribute('src', ''); // Now prepare our <noscript> markup $noscript = $dom->createElement("noscript"); // Insert it $noscriptNode = $image->parentNode->insertBefore($noscript, $image); // Append the image fallback $noscriptNode->appendChild($imageClone); } // Return our modified content $html = $dom->saveHTMLExact(); return $html; }
function html_beautifier($html) { if (!class_exists('SmartDOMDocument')) { require_once $this->plugin_path . 'vendors/SmartDOMDocument.class.php'; } $x = new SmartDOMDocument(); $x->loadHTML($html); $clean = $x->saveHTMLExact(); return $clean; }