2012-07-10 187 views
1

標籤href的值這是代碼我有,我想href值該ID獲取具有特定ID

function file_get_contents_curl($url){ 
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_HEADER, 0); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($ch, CURLOPT_URL, $url); 
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
      $data = curl_exec($ch); 
      curl_close($ch); 
      return $data; 
} 

    $str = 'someLink'; 
    $html = file_get_contents_curl($str); 
     $doc = new DOMDocument(); 
     libxml_use_internal_errors(true); 
     $doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . $html); 
     libxml_clear_errors(); 

     $nodes = $doc->getElementsByTagName('title'); 
     $hrefValue = $doc->getElementById('linker'); 

someLink HTML例如:

<html> 

<head> 
<title></title> 
</head> 

<body> 

<div>one</div> 

<div>two</div> 

<div> 
<a href="link" id="linker" />LINK HERE</a> 
</div> 

</body> 

</html> 

我想獲得id =「linker」的href值。我嘗試使用getElementById(),但它返回任何東西

回答

2
$nodes = $doc->getElementsByTagName('title')->item(0)->nodeValue; 
     $hrefValue = $doc->getElementById('linker')->getAttribute("href"); 
+0

致命錯誤:調用未定義的方法DOMElement :: item() – 2012-07-10 07:33:29

+0

如果我將其更改爲$ hrefValue = $ doc-> getElementById('linker') - > nodeValue;它返回鏈接在這裏我沒有得到鏈接文本 – 2012-07-10 07:35:25

+0

更新請參閱chnges – 2012-07-10 07:40:36

-1
preg_match('/href=[\'"]?(.+?)[\'"]?.*?id=[\'"]?linker[\'"]?/si', $subject, $matches); 
var_dump($matches); 
+0

「[基於正則表達式的HTML解析器是殺死StackOverflow的癌症](http://stackoverflow.com/questions/1732348/regex-match -open標籤 - 除了-XHTML-自足標籤)」 – feeela 2012-07-10 08:03:21

相關問題