如何打印元素的属性?
示例:
$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 ?
}
答案 0 :(得分:1)
$art->getAttribute('class');
另外,simpleHTMLDOM更适合处理html:
$html = str_get_html($page);
foreach($html->find('td') as $element)
echo $element->class.'<br>';
}
答案 1 :(得分:1)
DOMXPath
的query
函数返回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");
}
}