php DomDocument:我如何打印元素的属性?

时间:2010-07-10 17:05:18

标签: php dom xpath xpathquery

如何打印元素的属性?

示例:

$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 ?
}

2 个答案:

答案 0 :(得分:1)

使用DOMElement::getAttribute

$art->getAttribute('class');

另外,simpleHTMLDOM更适合处理html:

$html = str_get_html($page);
foreach($html->find('td') as $element) 
   echo $element->class.'<br>';
}

答案 1 :(得分:1)

DOMXPathquery函数返回DOMNodeList(我很确定)不能在foreach($ARRAY)循环中使用 [编辑:可以] 您必须实现修改后的for循环才能读取列表类中的DOMNode元素: [编辑:不必要;见下文]

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");
     }
}