2

I can get the attribute of the tag tragetting ID by:

$tag_id = $tag->getAttribute('id');

But I want to get all attributes, not just id. How can I do this? I tried getAttribute("*") but it did not work (obviously).

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • I dont have any experiences on it, but I found two posts from SO, http://stackoverflow.com/questions/2385834/php-dom-get-all-attributes-of-a-node, http://stackoverflow.com/questions/1338692/is-there-a-way-to-get-all-of-a-domelements-attributes, I hope it helps – Andrew Dec 29 '15 at 17:48

1 Answers1

4

You can use the public $attributes property from the DOMNode element that the DOMElement inherits from. See also here in the documentation: DOMNode::$attributes

Code example:

$document = <<<DOCUMENT
<div id='one' style='width: 10px'></div>
DOCUMENT;

$document = DOMDocument::loadXML($document);
$element = $document->getElementsByTagName('div')->item(0);

$attributes = $element->attributes;
for ($i = 0; $i < $attributes->length; $i++) {
    $item = $attributes->item($i);
    echo 'There is an attribute called: "' . $item->nodeName . '" with value: ' . $item->nodeValue . PHP_EOL;
}

See also the eval.in that I created: https://eval.in/494934

ArSeN
  • 5,133
  • 3
  • 19
  • 26