没错,HTML似乎没有缩进(其他人也很困惑)。即使加载了代码,XML仍然有效。
<?phpfunction 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解析它,
然后 漂亮地打印出来。据我记得这工作(但它 真的很 慢)。



