简体   繁体   中英

How can I retrieve infos from PHP DOMElement?

I'm working on a function that gets the whole content of the style.css file, and returns only the CSS rules that needed by the currently viewed page (it will be cached too, so the function only runs when the page was changed).

My problem is with parsing the DOM (I'm never doing it before with PHP DOM). I have the following function, but $element->tagname returns NULL. I also want to check the element's "class" attribute, but I'm stuck here.

function get_rules($html) {
    $arr = array();
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    foreach($dom->getElementsByTagName('*') as $element ){
        $arr[sizeof($arr)] = $element->tagname;
    }
    return array_unique($arr);
}

What can I do? How can I get all of the DOM elements tag name, and class from HTML?

Because tagname should be an undefined index because its supposed to be tagName (camel cased).

function get_rules($html) {

    $arr = array();
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    foreach($dom->getElementsByTagName('*') as $element ){
        $e = array();
        $e['tagName'] = $element->tagName; // tagName not tagname
        // get all elements attributes
        foreach($element->attributes as $attr) {
            $attrs = array();
            $attrs['name'] = $attr->nodeName;
            $attrs['value'] = $attr->nodeValue;
            $e['attributes'][] = $attrs;
        }
        $arr[] = $e;
    }
    return $arr;
}

Simple Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM