$doc = new DOMDocument(); $doc->loadHTML('This code loads an HTML document and retrieves the firstHello World
'); $node = $doc->getElementsByTagName('p')->item(0); if ($node->hasAttributes()) { // get attributes $attributes = $node->attributes; foreach ($attributes as $attr) { echo $attr->nodeName . ' = ' . $attr->nodeValue . '
'; } } else { echo 'This element has no attributes.'; }
element in it. Then, it checks whether the element has any attributes using the hasAttributes method. If it does, the code loops over the attributes and outputs their names and values. Otherwise, it prints a message saying there are no attributes. The package/library that this example belongs to is the PHP DOM extension.