Dom\HTMLDocument::createFromString
(PHP 8 >= 8.4.0)
Dom\HTMLDocument::createFromString — Parses an HTML document from a string
说明
public static Dom\HTMLDocument::createFromString(string
$source
, int $options
= 0, ?string $overrideEncoding
= null
): Dom\HTMLDocumentParses an HTML document from a string, according to the living standard.
参数
source
- The string containing the HTML to parse.
options
-
Bitwise
It is also possible to passOR
of the libxml option constants.Dom\HTML_NO_DEFAULT_NS
to disable the use of the HTML namespace and the template element. This should only be used if the implications are properly understood. overrideEncoding
- The encoding that the document was created in. If not provided, it will attempt to determine the encoding that is most likely used.
返回值
The parsed document as an Dom\HTMLDocument instance.
错误/异常
-
Throws a ValueError if
options
contains an invalid option. -
Throws a ValueError if
overrideEncoding
is an unknown encoding.
示例
示例 #1 Dom\HTMLDocument::createFromString() example
Parses a sample document.
<?php
$dom = Dom\HTMLDocument::createFromString(<<<'HTML'
<!DOCTYPE html>
<html>
<body>
<p>Hello, world!</p>
</body>
</html>
HTML);
echo $dom->saveHtml();
?>
以上示例会输出:
<!DOCTYPE html><html><head></head><body> <p>Hello, world!</p> </body></html>
注释
注意: Whitespace in the
html
andhead
tags is not considered significant and may lose formatting.
参见
- Dom\HTMLDocument::createEmpty() - Creates an empty HTML document
- Dom\HTMLDocument::createFromFile() - Parses an HTML document from a file
+添加备注
用户贡献的备注 1 note
kawewong at gmail dot com ¶
1 month ago
To load HTML without doctype, html, body elements use `LIBXML_HTML_NOIMPLIED` flag.
<?php
$html = <<<EOT
<div class="row">
<div class="col"><h1 id="heading" class="col1-heading">Hello</h1></div>
<div class="col"><p class="paragraph">Hello world.</p>
</div>
EOT;
$doc = \DOM\HTMLDocument::createFromString($html, LIBXML_HTML_NOIMPLIED);
echo htmlspecialchars($doc->saveHTML(), ENT_QUOTES);
?>
备份地址:http://www.lvesu.com/blog/php/dom-htmldocument.createfromstring.php