Search code examples
phpdomdomdocument

PHP: DomElement->getAttribute


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

$dom = new DOMDocument();
@$dom->loadHTML(http://www.example.com);

$a = $dom->getElementsByTagName("a");
echo $a->getAttribute('href');

thanks!


Solution

  • "Inspired" by Simon's answer. I think you can cut out the getAttribute call, so here's a solution 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);