30

我正在使用 PHP 中的 DOM 扩展来构建一些 HTML 文档,并且我希望输出的格式很好(带有新行和缩进),以便它可读,但是,从我所做的许多测试中:

  1. "formatOutput = true" 对 saveHTML() 根本不起作用,只有 saveXML()
  2. 即使我使用了 saveXML(),它仍然只适用于通过 DOM 创建的元素,而不是包含在 loadHTML() 中的元素,即使是“preserveWhiteSpace = false”

如果有人知道不同,我真的很想知道他们是如何让它工作的。

所以,我有一个 DOM 文档,我正在使用 saveHTML() 来输出 HTML。由于它来自 DOM,我知道它是有效的,因此无需“整理”或以任何方式验证它。

我只是在寻找一种方法来从我从 DOM 扩展收到的输出中获得格式良好的输出。

注意。正如您可能已经猜到的那样,我不想使用 Tidy 扩展作为 a) 它做的更多我也需要它(标记已经有效)并且 b) 它实际上对 HTML 内容进行了更改(例如HTML 5 文档类型和一些元素)。

跟进:

好的,在下面的答案的帮助下,我弄清楚了为什么 DOM 扩展不起作用。尽管给定的示例有效,但它仍然无法与我的代码一起使用。在此评论的帮助下,我发现如果您有任何 isWhitespaceInElementContent() 为 true 的文本节点,则不会应用超出该点的格式。无论preserveWhiteSpace 是否为假,都会发生这种情况。解决方案是删除所有这些节点(尽管我不确定这是否会对实际内容产生不利影响)。

4

3 回答 3

33

你是对的,HTML 似乎没有缩进(其他人也很困惑)。XML 可以工作,即使是加载了代码。

<?php
function tidyHTML($buffer) {
    // load our document into a DOM object
    $dom = new DOMDocument();
    // we want nice output
    $dom->preserveWhiteSpace = false;
    $dom->loadHTML($buffer);
    $dom->formatOutput = true;
    return($dom->saveHTML());
}

// start output buffering, using our nice
// callback function to format the output.
ob_start("tidyHTML");

?>
<html>
    <head>
    <title>foo bar</title><meta name="bar" value="foo"><body><h1>bar foo</h1><p>It's like comparing apples to oranges.</p></body></html>
<?php
// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();
?>

结果:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>foo bar</title>
<meta name="bar" value="foo">
</head>
<body>
<h1>bar foo</h1>
<p>It's like comparing apples to oranges.</p>
</body>
</html>

与 saveXML() 相同 ...

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
  <head>
    <title>foo bar</title>
    <meta name="bar" value="foo"/>
  </head>
  <body>
    <h1>bar foo</h1>
    <p>It's like comparing apples to oranges.</p>
  </body>
</html>

可能忘记在 loadHTML 之前设置 preserveWhiteSpace=false?

免责声明:我从tyson clugg/php 手动注释中窃取了大部分演示代码。懒我。


更新:我现在记得几年前我尝试过同样的事情并遇到了同样的问题。我通过应用一个肮脏的解决方法来解决这个问题(不是性能关键):我只是以某种方式在 SimpleXML 和 DOM 之间转换,直到问题消失。我想转换摆脱了那些节点。也许用 dom 加载,用 导入simplexml_import_dom,然后输出字符串,再次用 DOM 解析它,然后打印出来。据我记得这有效(但它真的很慢)。

于 2009-04-20T14:04:47.207 回答
3

结果:

<!DOCTYPE html>
<html>
    <head>
        <title>My website</title>
    </head>
</html>

请考虑:

function indentContent($content, $tab="\t"){
    $content = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $content); // add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
    $token = strtok($content, "\n"); // now indent the tags
    $result = ''; // holds formatted version as it is built
    $pad = 0; // initial indent
    $matches = array(); // returns from preg_matches()
    // scan each line and adjust indent based on opening/closing tags
    while ($token !== false && strlen($token)>0){
        $padPrev = $padPrev ?: $pad; // previous padding //Artis
        $token = trim($token);
        // test for the various tag states
        if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)){// 1. open and closing tags on same line - no change
            $indent=0;
        }elseif(preg_match('/^<\/\w/', $token, $matches)){// 2. closing tag - outdent now
            $pad--;
            if($indent>0) $indent=0;
        }elseif(preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)){// 3. opening tag - don't pad this one, only subsequent tags (only if it isn't a void tag)
            foreach($matches as $m){
                if (preg_match('/^<(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)/im', $m)){// Void elements according to http://www.htmlandcsswebdesign.com/articles/voidel.php
                    $voidTag=true;
                    break;
                }
            }
            $indent = 1;
        }else{// 4. no indentation needed
            $indent = 0;
        }

        if ($token == "<textarea>") {
            $line = str_pad($token, strlen($token) + $pad, $tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
            $result .= $line; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            $pad += $indent; // update the pad size for subsequent lines
        } elseif ($token == "</textarea>") {
            $line = $token; // pad the line with the required number of leading spaces
            $result .= $line . "\n"; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            $pad += $indent; // update the pad size for subsequent lines
        } else {
            $line = str_pad($token, strlen($token) + $pad, $tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
            $result .= $line . "\n"; // add to the cumulative result, with linefeed
            $token = strtok("\n"); // get the next token
            $pad += $indent; // update the pad size for subsequent lines
            if ($voidTag) {
                $voidTag = false;
                $pad--;
            }
        }           

    return $result;
}

//$htmldoc - DOMdocument Object!

$niceHTMLwithTABS = indentContent($htmldoc->saveHTML(), $tab="\t");

echo $niceHTMLwithTABS;

将产生具有以下内容的 HTML:

  • 基于“级别”的缩进
  • 块级元素后的换行符
  • 而内联和自闭合元素不受影响

该函数(这是我使用的类的一种方法)主要基于:https ://stackoverflow.com/a/7840997/7646824

于 2020-05-24T18:58:24.043 回答
-1

您可以使用htmLawed库的hl_tidy函数的代码。

// indent using one tab per indent, with all HTML being within an imaginary div
$out = hl_tidy($in, 't', 'div')
于 2012-08-13T14:37:01.340 回答