php DOMDocument: how can I print an attribute of an element?
Asked Answered
L

2

1

How do I print the an attribute of an element?

example:

$doc = new DOMDocument();
@$doc->loadHTML($page);
$xpath = new DOMXPath($doc);
$arts= $xpath->query("/td");

foreach ($arts as $art) {
   // here i wanna print the attribute class of the td element, how do i do so ?
}
Liberia answered 10/7, 2010 at 17:5 Comment(0)
S
1

use DOMElement::getAttribute

$art->getAttribute('class');

also, simpleHTMLDOM is more suitable for dealing with html:

$html = str_get_html($page);
foreach($html->find('td') as $element) 
   echo $element->class.'<br>';
}
Serviceable answered 10/7, 2010 at 17:8 Comment(1)
Care to elaborate why SimpleHtmlDom is "more suitable" than DOM for dealing with HTML? DOM handles HTML fine.Huppah
J
1

DOMXPath's query function returns a DOMNodeList, which (I'm pretty sure) cannot be used in a foreach($ARRAY) loop [Edit: it can]. You'll have to implement a modified for loop in order to read the DOMNode elements inside the list class: [Edit: not necessary; see below]

foreach ($arts as $art) {
     # code-hardiness checking
     if ($art && $art->hasAttributes()) {
         # (note: chaining will only work in PHP 5+)
         $class = $art->attributes->getNamedItem('class');
         print($class . "\n");
     }
}
Jae answered 10/7, 2010 at 17:16 Comment(3)
thanks for the info. just so you'll know, it does support foreach :)Liberia
Class [ <internal:dom> <iterateable> class DOMNodeList ] which means it can be used in a foreach constructHuppah
<td> is a DOMElement (not just a DOMNode), so $art->getAttribute('class') would suffice.Schott

© 2022 - 2024 — McMap. All rights reserved.