PHP simplehtmldom adding attributes

2019-08-02 08:07发布

For a project, I need to grab a page (ANY page on the internet) and manipulate it. I am using simplehtmldom for this (found here), since it is easy and works like a charm.. mostly.. I need to set a class attribute to certain elements, some of which do have a class attribute already, some of which don't. According to this article i found, you can add an attribute the following way:

$value = $e->attr['data-role'];

This, unfortunately, does not work for me. The following code gives these errors:

if(!isset($elem->class))
{
    $elem->attr['class'] = "classname";
}
else
{
    $elem->class = $elem->class . " classname";
}

Notice: Undefined offset: 2 in simplehtmldom.php on line 483
Notice: Undefined offset: 2 in simplehtmldom.php on line 488
Notice: Undefined offset: 2 in simplehtmldom.php on line 494

Which is the following in simplehtmldom:

function makeup()
{
    // text, comment, unknown
    if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);

    $ret = '<'.$this->tag;
    $i = -1;

    foreach ($this->attr as $key=>$val)
    {
        ++$i;
            // skip removed attribute
        if ($val===null || $val===false)
            continue;
/* 483 */   $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
        //no value attr: nowrap, checked selected...
        if ($val===true)
            $ret .= $key;
        else {
/* 488 */       switch ($this->_[HDOM_INFO_QUOTE][$i])
            {
                case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
                case HDOM_QUOTE_SINGLE: $quote = '\''; break;
                default: $quote = '';
            }
/* 494 */   $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
        }
    }
    $ret = $this->dom->restore_noise($ret);
    return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
}

I'm having some trouble figuring out why it won't work. Is it something that might have changed since the article was written, or am I doing something wrong here?

1条回答
▲ chillily
2楼-- · 2019-08-02 08:35

Turns out I was a little too early asking this question. I found this page (API reference) and it tells us we can use the following W3C standard too:

$e->setAttribute ( $name, $value )

So instead of

$elem->attr['class'] = "classname";

you can do

$elem->setAttribute("class","classname");

I'll keep the question and answer up in case other people come across this and miss the API reference page.

查看更多
登录 后发表回答