PHP: DomElement-> getAttribute

How can I take all the attributes of an element? As in my example below, I can only get one at a time, I want to pull out all the attribute of the anchor tag.

$dom = new DOMDocument(); @$dom->loadHTML(http://www.example.com); $a = $dom->getElementsByTagName("a"); echo $a->getAttribute('href'); 

thanks!

+7
dom php domdocument
source share
3 answers

β€œInspired,” Simon answered. I think you can cut the getAttribute call, so here without it:

 $attrs = array(); for ($i = 0; $i < $a->attributes->length; ++$i) { $node = $a->attributes->item($i); $attrs[$node->nodeName] = $node->nodeValue; } var_dump($attrs); 
+8
source share
 $length = $a->attributes->length; $attrs = array(); for ($i = 0; $i < $length; ++$i) { $name = $a->attributes->item($i)->name; $value = $a->getAttribute($name); $attrs[$name] = $value; } print_r($attrs); 
+10
source share
 $a = $dom->getElementsByTagName("a"); foreach($a as $element) { echo $element->getAttribute('href'); } 
+1
source share

All Articles