简单的HTML dom解析器:修复属性缺少引号的问题


simple html dom parser: fix missing quotes of attributes

我正在使用简单的HTML dom解析器来批量修复HTML标记中的错误,例如缺少引号,如

<div class=foo></div>
我代码:

$els = $doc->find("div[class]");
foreach($els as $el)
{
    $class = $el->getAttribute("class");
    $el->setAttribute("class", "'"".$class."'"");
}

可以工作,但缺点是它不适用于已经有引号的元素。<div class="foo"></div>将导致<div class='"foo"'></div>,这对我来说似乎是一个bug。我也不能检查类是否被引用,因为解析器只返回没有引号的字符串,我也不想使用outertext,因为可能有其他属性需要考虑。

有什么办法解决这个问题吗?

谢谢

基本上,您只需要将属性重置为字符串,显然,如果属性不是字符串,则去掉双引号。

所以为了将来的参考和其他人,你可以这样做:

$els = $doc->find("div[class]");
foreach($els as $el) {
    $class = $el->getAttribute("class");
    $el->setAttribute("class", strval($class));
}

或者您可以尝试将所有属性设置为字符串:

    foreach($html->find('your selector here') as $elem) {
        
        # check if there are attributes
        if (is_object($elem) && isset($elem->attr)) {
            
            # loop through all attributes
            foreach ($elem->attr as $key=>$val) {
                    
                # normalize attributes, but skip empty, integers and boolean values
                if(!empty($val) && !is_int($val) && !is_bool($val)) {
                    $elem->{$key} = strval($elem->{$key});
                }   
            }                   
        }
    }