2015-04-06 65 views
1

我需要從這個下面的代碼片段DOM文檔來獲取href和的nodeValue

<a class="head_title" href="/automotive/pr?sid=0hx">Automotive</a> 

獲取的nodeValue和HREF要做到這一點我也做了以下內容:

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

任何人都可以請幫我這。

回答

0

hasAttribute是DOMElements的有效方法,但不能將其用於文本節點。你可以檢查節點的類型,然後嘗試提取值是它不是'文本'節點。下面的代碼可以幫助你

foreach($p->childNodes as $child) { 
    $name = $child->nodeValue; 

    echo $name ."<br />"; 
    if ($child->nodeType == 1) { 
     echo $child->hasAttribute('href'); 
    } 
} 

它檢查節點是'DOMElement'類型和調用hasAttribute方法,只有當它是一個DOMElement。

+0

@Diptendu ...在做以下編碼時:foreach($ dom-> getElementsByTagName('a')as $ p){ 如果($ p-> getAttribute('class')=='head_title' ){ \t \t \t 的foreach \t($對 - >的childNodes爲$子){ \t \t \t $ NAME = $兒童安全>的nodeValue; \t \t \t \t \t \t如果($兒童安全>節點類型== 1){ 回聲$兒童安全> hasAttribute( 'href' 屬性); } \t \t \t \t} \t \t \t}} 它給了我一個空白頁 – user3305327 2015-04-06 10:03:48

+0

你看到任何PHP的致命錯誤?我無法測試這個,因爲我沒有PHP設置。讓我知道如果有什麼辦法,我可以在一些小提琴上嘗試一下。 – Diptendu 2015-04-06 11:16:51

0

是的......我做了改變我的編碼如下所示:

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

而且這對我的作品!