2015-10-30 70 views
0

我有以下test.php文件,当我运行它时,关闭</h1>标记被删除。DOMDocument删除脚本标记内的结束标记

<?php 

$doc = new DOMDocument(); 

$doc->loadHTML('<html> 
    <head> 
     <script> 
      console.log("<h1>hello</h1>"); 
     </script> 
    </head> 
    <body> 

    </body> 
</html>'); 

echo $doc->saveHTML(); 

下面是结果,当我执行该文件:

PHP Warning: DOMDocument::loadHTML(): Unexpected end tag : h1 in Entity, line: 4 in /home/ryan/NetBeansProjects/blog/test.php on line 14 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html> 
    <head> 
     <script> 
      console.log("<h1>hello"); 
     </script> 
    </head> 
    <body> 
    </body> 
</html> 

那么,为什么它删除代码?这是一个字符串,所以不应该忽略它?

+0

作为一个猜测,我认为标签被删除,因为它在脚本元素中,所以斜线可能需要转义。尝试将

hello

放在体内,看看会发生什么。 – jeff

+0

它在身体中做同样的事情。但是我读过,'loadXML()'支持这个。我试过了,它并没有删除标签,但是当我加载外部html文件时,我的错误是无效的。 –

+0

如果你反转你的引号,或者像这样''console.log(\“

hello

\”);' –

回答

1

想到的是浸渍料配合脚本标记,然后用临时支架代替他们喜欢<script id="myuniqueid"></script>和DOM管理的最终唯一的解决方案与实际脚本再次更换,就像这样:

// The dom doc 
$doc = new DOMDocument(); 

// The html 
$html = '<html> 
    <head> 
     <script> 
      console.log("<h1>hello</h1>"); 
     </script> 
    </head> 
    <body> 

    </body> 
</html>'; 

// Patter for scripts 
$pattern = "/<script([^']*?)<\/script>/"; 
// Get all scripts 
preg_match_all($pattern, $html, $matches); 

// Only unique scripts 
$matches = array_unique($matches[0]); 

// Construct the arrays for replacement 
foreach ($matches as $match) { 
    // The simple script 
    $id = uniqid('script_'); 
    $uniqueScript = "<script id=\"$id\"></script>"; 
    $simple[] = $uniqueScript; 
    // The complete script 
    $complete[] = $match; 
} 

// Replace the scripts with the simple scripts 
$html = str_replace($complete, $simple, $html); 
// load the html into the dom 
$doc->loadHTML($html); 

// Do the dom management here 
// TODO: Whatever you do with the dom 

// When finished 
// Get the html back 
$html = $doc->saveHTML(); 
// Replace the scripts back 
$html = str_replace($simple, $complete, $html); 
//Print the result 
echo $html; 

此解决方案打印干净无dom错误。