禁用DOMDocument以格式化代码

时间:2013-11-29 01:40:01

标签: php dom domdocument

如何让DomDocument不在内容中插入p标签?

我使用此代码:

$content = 'http://google.com';

// New DOM
$document = new DOMDocument();
$document->recover = false;
@$document->loadHTML( $content );
$content = $document->saveHTML();

print_r( $content );

没有帮助,输出是:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>http://google.com</p></body></html>

我希望它是:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>http://google.com</body></html>

这可能吗?

1 个答案:

答案 0 :(得分:0)

$content = 'http://google.com';

// New DOM
$document = new DOMDocument();
$document->recover = false;
@$document->loadHTML( $content );

// Copy contents of <p> to <body>
$body = $document->getElementsByTagName("body")->item(0);
$p = $document->getElementsByTagName("p")->item(0);
foreach ($p->childNodes as $e) {
    $body->appendChild($e);
}
$body->removeChild($p);
// Resume OP's code

$content = $document->saveHTML();

print_r( $content );