Php strip template


Php strip template

我有一些html模板的格式是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head> 
    <title>myTitle</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   
</head> 
<body bgcolor="#b23bba" style="background-color: #b23bba; margin: 0;"> 
    <table>
        <tr><td><img src="https://www.myurlname.com/anotherimg.jpg" /></td></tr>
        <tr><td>needed content</td></tr>
    </table>
    <img src="https://www.myurlname.com/e68f2e83c811d6bdb32876041a1cfa78.gif" width="1" height="1" />
</body>
</html>

需要做的是剥离这个模板,只取其中的一部分,并将其插入另一个模板中,该模板已经有html、head或body等html通用标签。我需要的是只保留我在身体标签之间的东西,但没有图像,因为图像的高度和宽度是1倍。

对于这种特殊情况,我只能保留桌子。我必须提到,我将所有这些内容存储到一个php变量中。有什么解决办法吗?

考虑到您有一个完整有效的DOM,您可以解析它,查询<body>节点,并存储它。它只需要几行代码,使用DOMDocument类:

$dom = new DOMDocument;
$dom->loadHTML($str);
$contents = $dom->getElementsByTagName('body')->item(0);
$bodyContents = $dom->saveXML($contents);

这将产生:

<body><!-- your markup here --></body>

为了去掉body标签,一个简单的substr调用将执行以下操作:

$clean = substr($bodyContents, 6, -7);

就这样!下面是一个更完整的例子BTW.

当然,如果您的<body>标记可能包含属性,则必须首先删除这些属性。一般来说,这样的东西应该有效:

$body = $dom->getElementsByTagName('body')->item(0);
if ($body->hasAttributes())
{
    foreach($body->attributes as $attr)
    {
        $body->removeAttributeNode($attr);
    }
}

这一切在这里都有很好的记录,在官方的PHP页面上

事实证明,foreach并没有完全切割它,所以这里是完整的固定代码:

$dom = new DOMDocument;
//avoid unwanted HTML entities (like &#13;) from popping up:
$str = str_replace(array("'n", "'r"), '', $str);
$dom->loadHTML($str);
$contents = $dom->getElementsByTagName('body')->item(0);
while($contents->hasAttributes())
{//as long as hasAttributes returns true, remove the first of the list
    $contents->removeAttributeNode($contents->attributes->item(0));
}
//remove last image:
$imgs = $contents->getElementsByTagName('img');//get all images
if ($imgs && $imgs->length)
{//if there are img tags:
    $contents->removeChild($imgs->item($imgs->length -1));//length -1 is last element
}
$bodyContents = $dom->saveXML($contents);
$clean = trim(substr($bodyContents, 6, -7));//remove <body> tags

这是它有效的证据
现在,一个没有那些烦人的HTML实体的版本

现在,最后,一个从DOM中删除最后一个img标记的代码板,也是