我需要从以下代码段中获取nodeValue和HREF
<a class="head_title" href="/automotive/pr?sid=0hx">Automotive</a>
为了实现这一点,我做了以下工作:
foreach($dom->getElementsByTagName('a') as $p) {
if($p->getAttribute('class') == 'head_title') {
foreach($p->childNodes as $child) {
$name = $child->nodeValue;
echo $name ."<br />";
echo $child->hasAttribute('href');
}
}
}
它返回给我一个错误:
PHP Fatal error: Call to undefined method DOMText::hasAttribute()
有人能帮我吗。
hasAttribute是DOMElement的有效方法,但不能用于文本节点。你能检查节点的类型,然后尝试提取值吗?它不是一个"文本"节点。以下代码可能有助于
foreach($p->childNodes as $child) {
$name = $child->nodeValue;
echo $name ."<br />";
if ($child->nodeType == 1) {
echo $child->hasAttribute('href');
}
}
它检查节点是否为"DOMElement"类型,并且仅当它是DOMElement时才调用hasAttribute方法。
是。。。我在编码中做了如下更改:
foreach($dom->getElementsByTagName('a') as $link) {
if($link->getAttribute('class') == 'head_title') {
$link2 = $link->nodeValue;
$link1 = $link->getAttribute('href');
echo "<a href=".$link1.">".$link2."</a><br/>";
}
}
它对我有用!