Load HTML from string

@param string $html

@return Document
@throws InvalidArgumentException if argument is not string
8149
public function loadHtml($html)
    {
        if (!is_string($html)) {
            throw new InvalidArgumentException(__METHOD__ . ' expects parameter 1 to be string.');
        }

        libxml_use_internal_errors(true);
        libxml_disable_entity_loader(true);

        $sxe = simplexml_load_string($html);
        if (libxml_get_errors()) {
            $this->document->loadHTML('<?xml encoding="UTF-8">' . $html);
        } else {
            $this->document = dom_import_simplexml($sxe)->ownerDocument;
        }

        libxml_clear_errors();
        libxml_disable_entity_loader(false);
        libxml_use_internal_errors(false);

        return $this;
    }
1246580
public function loadHTML($html)
    {
        $dom = new \DOMDocument();
        $dom->formatOutput = true;

        // strip illegal XML UTF-8 chars
        // remove all control characters except CR, LF and tab
        $html = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', '', $html); // 00-09, 11-31, 127

        $dom->loadHTML($html);
        $this->loadDomDocument($dom);
    }
1168606
public static function fromString(string $xml) : DOMDocument
    {
        if (trim($xml) === '') {
            throw InvalidArgumentException::invalidType('non-empty string', $xml);
        }

        $entityLoader = libxml_disable_entity_loader(true);
        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $domDocument = self::create();
        $options = LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NONET;
        if (defined('LIBXML_COMPACT')) {
            $options |= LIBXML_COMPACT;
        }

        $loaded = $domDocument->loadXML($xml, $options);

        libxml_use_internal_errors($internalErrors);
        libxml_disable_entity_loader($entityLoader);

        if (!$loaded) {
            $error = libxml_get_last_error();
            libxml_clear_errors();

            throw new UnparseableXmlException($error);
        }

        libxml_clear_errors();

        foreach ($domDocument->childNodes as $child) {
            if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                throw new RuntimeException(
                    'Dangerous XML detected, DOCTYPE nodes are not allowed in the XML body'
                );
            }
        }

        return $domDocument;
    }
1040653
public static function fromString($string)
    {
        $okay = strlen($string) < 256;
        Assertion::true($okay, 'StreamId cannot be greater than 255 chars.', 'StreamId');
        if (!preg_match(self::VALID_PATTERN, $string, $matches)) {
            throw new InvalidArgumentException(
                sprintf(
                    'StreamId [%s] is invalid.  It must match the pattern [%s].',
                    $string,
                    self::VALID_PATTERN
                )
            );
        }

        return new self(
            $matches[1],
            isset($matches[3]) ? $matches[3] : null,
            isset($matches[5]) ? $matches[5] : null
        );
    }
1334815
protected function getHtmlDescription($html)
    {
        $content = '';
        $doc = new \DOMDocument;
        @$doc->loadHTML($html);
        $xpath = new \DOMXPath($doc);

        $query = '//p[preceding-sibling::p]';

        foreach ($xpath->query($query) as $node) {
            $content .= trim($node->textContent, PHP_EOL);
        }

        return $content;
    }
1282640
public function setHtml($Html)
    {
        if (! is_object($Html) || ! $Html instanceof HtmlObject) {
            throw new \InvalidArgumentException(
                'The HTML Object must be a valid HTML Object'
            );
        }
        $this->Html = $Html;

        return true;
    }
1340746
function parse($html)
		{
			$dom = new \DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($html);
			$xpath = new \DOMXPath($dom);
			
			// Load resources for tag actions
			$this->ignoreElements = new ResourceProvider("html_tag_actions/ignore.lst");
			$this->linkElements = new ResourceProvider("html_tag_actions/link.lst");
			$this->bodyElements = new ResourceProvider("html_tag_actions/body.lst");
			$this->inlineElements = new ResourceProvider("html_tag_actions/inline.lst");
			
			/*	
			 *  1st retrieve page title
			 *  With this technique: only process the entire document here 
			 *  as meta is excluded as 'content' and only required for initial title.
			 */

			// Extract title from DOM
			$body = $xpath->query('/')->item(0);
			$titleItem = $xpath->query('//title')->item(0);
			
			if(isset($titleItem))
			{
				$title = $titleItem->textContent;
			}
			$body = $xpath->query('//body')->item(0);
			
			// Try to extract title from OG meta
			foreach ($xpath->query("//meta[@property='og:title']") as $el) 
			{
				$title = $el->getAttribute("content");
			}
			
			$this->recurse($body);
			$Article = new Article();
			if(isset($title))
			{
				$Article->title = $title;
			}
			$Article->textBlocks = $this->textBlocks;
			return $Article;
		}
538135
public function convert($html)
    {
        $html = parent::convert((string) $html);

        $html = $this->encode('--', '-', $html, false);
        $html = $this->encode('\#', '#', $html);
        $html = $this->encode('\*', '*', $html);
        $html = $this->encode('\_', '_', $html);
        $html = $this->encode('•', '*', $html);
        $html = $this->encode('…', '...', $html);

        $html = $this->encode('\[', '[', (string) $html);
        $html = $this->encode('\]', ']', (string) $html);
        $html = str_replace(array('—', '–', '\-'), '-', $html);
        $html = str_replace(array('“', '”'), '"', $html);
        $html = str_replace(array('’', '‘'), "'", $html);
        $html = str_replace("\n\n\n", "\n\n", $html);
        $html = str_replace("\n ", "\n", (string) $html);

        return str_replace('\.', '.', (string) $html);
    }
592768
protected function gernerate_pdf($html)
    {
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->set_option("compressed", true);
        $dompdf->set_option('defaultFont', 'sans-serif');
        $dompdf->set_option('isHtml5ParserEnabled', true);
        return $dompdf;
    }
54900
protected function createDomDocument($html): \DOMDocument
    {
        $document = new \DOMDocument('1.0');
        $previousValue = libxml_use_internal_errors(true);
        libxml_clear_errors();
        $document->loadHTML($html);
        /** @var \LibXMLError[] $errors */
        $errors = libxml_get_errors();
        libxml_clear_errors();
        libxml_use_internal_errors($previousValue);

        foreach ($errors as $error) {
            if (LIBXML_ERR_ERROR === $error->level || LIBXML_ERR_FATAL === $error->level) {
                throw new SourceException(
                    sprintf('%s at %d:%d', trim($error->message), $error->line, $error->column),
                    $error->code
                );
            }
        }

        return $document;
    }
1082141
private function loadDOMDocument($content)
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->encoding = 'UTF-8';

        $dom->strictErrorChecking = false;
        $dom->substituteEntities = false;
        $dom->formatOutput = false;

        // Change mb and libxml config
        $libxmlCurrent = libxml_use_internal_errors(true);
        $mbDetectCurrent = mb_detect_order();
        mb_detect_order('ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15');

        $loaded = $dom->loadHTML($this->fixContentEncoding($content));

        // Restore mb and libxml config
        libxml_use_internal_errors($libxmlCurrent);
        mb_detect_order(implode(',', $mbDetectCurrent));

        if (!$loaded) {
            throw new InvalidMarkupException("Can't load the given HTML via DomDocument");
        }

        return $dom;
    }
1188414
public function convertToString($html)
    {
        $externalJavaScript = $this->extractExternalJavaScript($html);

        return $this->replaceJavaScriptTags($html, $externalJavaScript);
    }
490279
protected function parseHtml($html)
    {
        $data = [
            'image' => '',
            'title' => '',
            'description' => '',
            'pictures' => [],
        ];

        libxml_use_internal_errors(true);
        $doc = new \DOMDocument();
        $doc->loadHTML($html);

        /** @var \DOMElement $meta */
        foreach ($doc->getElementsByTagName('meta') as $meta) {
            if ($meta->getAttribute('itemprop') === 'image') {
                $data['image'] = $meta->getAttribute('content');
            } elseif ($meta->getAttribute('property') === 'og:image') {
                $data['image'] = $meta->getAttribute('content');
            } elseif ($meta->getAttribute('property') === 'twitter:image') {
                $data['image'] = $meta->getAttribute('value');
            }

            if ($meta->getAttribute('itemprop') === 'name') {
                $data['title'] = $meta->getAttribute('content');
            } elseif ($meta->getAttribute('property') === 'og:title') {
                $data['title'] = $meta->getAttribute('content');
            } elseif ($meta->getAttribute('property') === 'twitter:title') {
                $data['title'] = $meta->getAttribute('value');
            }

            if ($meta->getAttribute('itemprop') === 'description') {
                $data['title'] = $meta->getAttribute('content');
            }
            if ($meta->getAttribute('property') === 'og:description') {
                $data['description'] = $meta->getAttribute('content');
            }
        }

        if (empty($data['title'])) {
            /** @var \DOMElement $title */
            foreach ($doc->getElementsByTagName('title') as $title) {
                $data['title'] = $title->nodeValue;
            }
        }

        if (empty($data['description'])) {
            foreach ($doc->getElementsByTagName('meta') as $meta) {
                if ($meta->getAttribute('name') === 'description') {
                    $data['description'] = $meta->getAttribute('content');
                }
            }
        }

        foreach ($doc->getElementsByTagName('img') as $img) {
            $data['pictures'][] = $img->getAttribute('src');
        }

        return $data;
    }
1165483
public function read($string)
	{
		if ( ! is_string($string)) {
			throw new \InvalidArgumentException(
				__METHOD__."() expects parameter one, string, to be a string"
			);	
		}
		
		// fake the snippet as a "root" group
		$string = '{'.$string.'}';
		
		// instantiate the string's chunker and stream
		$chunker = new \Jstewmc\Chunker\Text($string);
		$stream  = new \Jstewmc\Stream\Stream($chunker);	
		
		// lex the stream
		$tokens  = (new Lexer())->lex($stream);
		
		// parse and render the tokens
		$group = (new Renderer())->render((new Parser())->parse($tokens));
		
		// set the snippet's properties from the group
		$this->parent     = null;
		$this->children   = $group->getChildren();
		$this->style      = $group->getStyle();
		$this->isRendered = true;
		
		return (bool) $group;
	}
286854
public function html($html = null)
    {
        if ($html === null) {
            return $this->_html;
        }
        $this->_html = $html;

        return $this;
    }
244160
private function parseAttributes(string $html): string
    {
        $remainingHtml = \mb_substr($html, mb_strlen($this->name) + 1);
        while (\mb_strpos($remainingHtml, '>') !== false && preg_match("/^\s*[\/]?>/", $remainingHtml) === 0) {
            $remainingHtml = $this->parseAttribute($remainingHtml);
        }

        return $remainingHtml;
    }
874871
public function setHtml($html = null)
    {
        $html = trim($html);
        $this->html = 0 < strlen($html) ? $html : null;

        return $this;
    }