(PHP 5)

DOMDocument::saveHTML Сохраняет документ из внутреннего представления в строку, используя HTML форматирование


public string DOMDocument::saveHTML ([ DOMNode $node = NULL ] )

Создает HTML документ из DOM представления. Эту функцию обычно вызывают после построения нового DOM документа, как показано в примере ниже.

Список параметров


Необязательный аргумент для вывода некоторого подмножества документа.

Возвращаемые значения

Возвращает HTML или FALSE в случае ошибки.

Список изменений

Версия Описание
5.3.6 Добавлен аргумент node.


Пример #1 Сохранение HTML дерева в виде строки


= new DOMDocument('1.0');

$root $doc->createElement('html');
$root $doc->appendChild($root);

$head $doc->createElement('head');
$head $root->appendChild($head);

$title $doc->createElement('title');
$title $head->appendChild($title);

$text $doc->createTextNode('Это заголовок');
$text $title->appendChild($text);



Смотрите также


// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <>
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
// load our document into a DOM object
$dom = @DOMDocument::loadHTML($buffer);
// we want nice output
$dom->formatOutput true;

// start output buffering, using our nice
// callback funtion to format the output.

<p>It's like comparing apples to oranges.

// this will be called implicitly, but we'll
// call it manually to illustrate the point.


The above code takes out sloppy HTML:
 <p>It's like comparing apples to oranges.

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">
 <html><body><p>It's like comparing apples to oranges.
2005-04-21 20:44:56

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
2007-11-20 13:07:44
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

('Content-Type: text/html; charset=iso-8859-1');
2007-11-27 17:28:44
DOMDocument->saveXML() doesn't generate a proper XHTML format either.

There is a problem with "script" empty elements. For example:

This will be the code generated by saveXML, with an empty script tag.

    <script type="text/JavaScript" src="myScript.js"/>
    <p>I will not appear</p>
    <script type="text/JavaScript">
    alert("Not working");

I don't know if this is valid XHTML (W3C Validator doesn't complain), but both FF 2.0 and IE 6 will not render it properly. Both will use </script> as the closing tag for the first script causing js errors and ignoring in between elements.

You can post-process saveXML string in order to close empty tags with the following function:

function cerrarTag($tag$xml){
$indice 0;
        while (
$pos strpos($xml"<$tag "$indice);
            if (
$posCierre strpos($xml">"$pos);
                if (
$xml[$posCierre-1] == "/"){
$xml substr_replace($xml"></$tag>"$posCierre-12);
$indice $posCierre;
            else break;

At least script and select empty elements should be closed. This example shows how it can be used:

("CABECERA_XHTML"'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">');

$xhtml $docXML->saveXML($docXML->documentElement);
$xhtml cerrarTag("script"$xhtml);
$xhtml cerrarTag("select"$xhtml);
$xhtml CABECERA_XHTML."\n".$xhtml;
2008-02-19 13:34:37
function getDOMString($retNode) {
  if (!
$retNode) return null;
$retval strtr($retNode-->ownerDocument->saveXML($retNode),
'></area>' => ' />',
'></base>' => ' />',
'></basefont>' => ' />',
'></br>' => ' />',
'></col>' => ' />',
'></frame>' => ' />',
'></hr>' => ' />',
'></img>' => ' />',
'></input>' => ' />',
'></isindex>' => ' />',
'></link>' => ' />',
'></meta>' => ' />',
'></param>' => ' />',
'default:' => ''
// sometimes, you have to decode entities too...
'&quot;' => '&#34;',
'&amp;' =>  '&#38;',
'&apos;' => '&#39;',
'&lt;' =>   '&#60;',
'&gt;' =>   '&#62;',
'&nbsp;' => '&#160;',
'&copy;' => '&#169;',
'&laquo;' => '&#171;',
'&reg;' =>   '&#174;',
'&raquo;' => '&#187;',
'&trade;' => '&#8482;'
2008-04-25 23:15:25
This method, as of 5.2.6, will automatically add <html><body> and <!DOCTYPE> tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here's a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
2008-08-18 11:41:41
I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

'<h1>Hello world!</h1>';
$html '<div>' $html '</div>';
$doc = new DOMDocument;
substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6)

// Outputs: "<h1>Hello world!</h1>"
2009-01-18 12:17:23
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:


= new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */ 
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") { 
$xpath = new DOMXpath($doc);
$resultlist $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
foreach($resultlist as $headnode// insert the script tag
$doc->saveXML(); /* and our script tags will still be <script></script> */

2009-05-12 22:35:54
If you want a simpler way to get around the <script> tag problem try:


$doc->createElement ('script');
// Creating an empty text node forces <script></script>
$script->appendChild ($doc->createTextNode (''));
$head->appendChild ($script);

2010-02-09 09:52:04
Another way to workaround the <script/> problem is putting a semicolon (;) inside the script element.
2010-11-24 09:21:13
Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():
2011-03-29 14:04:18
In this post I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    return $doc->saveHTML();
2014-11-11 18:34:39
Tested in PHP 5.2.9-2 and PHP 5.2.17. 
saveHTML() игнорирует свойство DOMDocument->encoding. Метод saveHTML() сохраняет html-документ в кодировке, которая указана в теге <meta> исходного (загруженного) html-документа. 
saveHTML() ignores property DOMDocument->encoding. Method saveHTML() saves the html-document encoding, which is specified in the tag <meta> source (downloaded) html-document. 
file.html. Кодировка файла должна совпадать с указанной в теге <meta>. The encoding of the file must match the specified tag <meta>. 
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Russian language</title></head>
<body>Русский язык</body></html>

$document=new domDocument('1.0''UTF-8'); 
"Записано байт. Recorded bytes: ".file_put_contents('file_new.html'$htm);
file_new.html будет в кодировке Windows-1251 (НЕ в UTF-8). 
file_new.html will be encoded in Windows-1251 (not in UTF-8). 

saveHTML() и file_put_contents() позволяют преодолеть недостаток метода saveHTMLFile(). 
Смотрите мой комментарий к методу saveHTMLFile(). 
saveHTML() and file_put_contents() allows you to overcome the lack of a method saveHTMLFile(). 
See my comment on the method saveHTMLFile().
2015-04-29 18:49:33
To solve the script tag problem just add an empty text node to the script node and DOMDocument will render <script src="your.js"></script> nicely.
2015-12-11 17:38:53
As of PHP 5.4 and Libxml 2.6, there is currently simpler approach:

when you load html as this


in the output, there will be no doctype, html or body tags
2016-08-20 15:34:27
If you load HTML from a string ensure the charset is set.

$html_src '<html><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type"></head><body>';
$html_src .= '...';

Otherwise the charset will be ISO-8859-1!
2016-08-31 13:41:05
When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being "broken" as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment. 

For an example:


will end up as:


Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML('<html>' . $content .'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array('<html>','</html>') , '' , $html->saveHTML());
2017-07-27 19:21:24
LIBXML_HTML_NOIMPLIED doesn't work on PHP 7.1.9 with libxml2-2.7.8
2017-09-28 05:57:12

    Поддержать сайт на родительском проекте КГБ