Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 711
Loreto Gabawa Jr. Avatar asked Feb 24 '10 16:02

Loreto Gabawa Jr.


3 Answers

"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);
like image 145
middus Avatar answered Oct 12 '22 18:10

middus


$a = $dom->getElementsByTagName("a");
foreach($a as $element)
{
   echo $element->getAttribute('href');
}
like image 39
a1ex07 Avatar answered Oct 12 '22 18:10

a1ex07


$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);
like image 30
Simon Avatar answered Oct 12 '22 16:10

Simon