Search code examples
phpdomxpathxpathquery

php DOMDocument: how can I print an attribute of an element?


How do I print the an attribute of an element?

example:

$doc = new DOMDocument();
@$doc->loadHTML($page);
$xpath = new DOMXPath($doc);
$arts= $xpath->query("/td");

foreach ($arts as $art) {
   // here i wanna print the attribute class of the td element, how do i do so ?
}

Solution

  • use DOMElement::getAttribute

    $art->getAttribute('class');
    

    also, simpleHTMLDOM is more suitable for dealing with html:

    $html = str_get_html($page);
    foreach($html->find('td') as $element) 
       echo $element->class.'<br>';
    }