views:

417

answers:

3

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!

+1  A: 
$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);
Simon
A: 
$a = $dom->getElementsByTagName("a");
foreach($a as $element)
{
   echo $element->getAttribute('href');
}
a1ex07
If I read the question right, he wants all the element's attributes.Not one attrbiute from all elements.
Simon
oops... You are right, my bad.
a1ex07
+2  A: 

"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);
middus
I feel robbed of the accepted answer :) Good spot though.
Simon