使用 tidy 获取没有标签的 body
Get body without tags using tidy
http://php.net/manual/en/tidy.body.php 将 return 正文内容包裹在 <body>
标签中。如何在没有 <body>
标签的情况下获取正文内容?我想出了几个可能的解决方案,但是,它们不是很优雅。
$tidy = new tidy;
$tidy->parseString($html);
$tidy->cleanRepair();
$body_content=trim(ltrim(rtrim(trim($tidy->body()->value),'</body>'),'<body>'));
var_dump($body_content);
$body=$tidy->body()->value;
$body_content=substr($body,7,strlen($body)-16);
var_dump($body_content);
$tidy->body()
returns 代表正文的 tidyNode
实例。每个 tidyNode
包含一个 child
属性,每个子元素包含一个 tidyNode
实例数组。您可以遍历这些子项以重建 body 标记的内部 html。例如:
<?php
$html = <<<'HTML'
<html>
<head><title>test</title></head>
<body>
<h1>Hello!</h1>
<p>Hello world!</p>
</body>
</body>
</html>
HTML;
$tidy = new tidy;
$tidy->parseString($html);
$tidy->cleanRepair();
$bodyInnerHtml = '';
foreach($tidy->body()->child as $child) {
$bodyInnerHtml .= (string)$child;
}
var_dump($bodyInnerHtml);
将导致:
string(36) "<h1>Hello!</h1>
<p>Hello world!</p>
"
有关 tidyNode
class 的更多信息,请参见 documentation。
http://php.net/manual/en/tidy.body.php 将 return 正文内容包裹在 <body>
标签中。如何在没有 <body>
标签的情况下获取正文内容?我想出了几个可能的解决方案,但是,它们不是很优雅。
$tidy = new tidy;
$tidy->parseString($html);
$tidy->cleanRepair();
$body_content=trim(ltrim(rtrim(trim($tidy->body()->value),'</body>'),'<body>'));
var_dump($body_content);
$body=$tidy->body()->value;
$body_content=substr($body,7,strlen($body)-16);
var_dump($body_content);
$tidy->body()
returns 代表正文的 tidyNode
实例。每个 tidyNode
包含一个 child
属性,每个子元素包含一个 tidyNode
实例数组。您可以遍历这些子项以重建 body 标记的内部 html。例如:
<?php
$html = <<<'HTML'
<html>
<head><title>test</title></head>
<body>
<h1>Hello!</h1>
<p>Hello world!</p>
</body>
</body>
</html>
HTML;
$tidy = new tidy;
$tidy->parseString($html);
$tidy->cleanRepair();
$bodyInnerHtml = '';
foreach($tidy->body()->child as $child) {
$bodyInnerHtml .= (string)$child;
}
var_dump($bodyInnerHtml);
将导致:
string(36) "<h1>Hello!</h1>
<p>Hello world!</p>
"
有关 tidyNode
class 的更多信息,请参见 documentation。