Viewed   195 times

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();

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




"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;
Thursday, September 29, 2022


Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

Monday, September 12, 2022

15 seconds to create and json_encode 10K elements .. this can't be right. The bottle neck is undoubtedly not PHP here. Where is that data coming from, a database ? In a single query or embedded queries in a loop ? Can the data be cached ? If so, do so.

You need to properly benchmark before optimizing, what you're trying to do now is trim milliseconds off an operation that takes 15 seconds.

Friday, August 12, 2022

I'm afraid not. You'll have to iterate through the children or use XPath.

for ($n = $parent->firstChild; $n !== null; $n = $n->nextSibling) {
    if ($n instanceof DOMElement && $n->tagName == "xxx") {

Example with XPath and your XML file:

$xml = ...;
$d = new DOMDocument();
$cat = $d->getElementsByTagName("subCategory")->item(0);
$xp = new DOMXpath($d);
$q = $xp->query("id", $cat); //note the second argument
echo $q->item(0)->textContent;

gives 2.

Thursday, September 15, 2022

Well, nodeValue will give you the node's value. You want what's commonly called outerHTML

echo $dom->saveXml($tag);

will output what you are looking for in an X(HT)ML compliant way.

As of PHP 5.3.6 you can also pass a node to saveHtml, which wasnt possible previously:

echo $dom->saveHtml($tag);

The latter will obey HTML4 syntax. Thanks to Artefacto for that.

Tuesday, December 27, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :