2012-07-10 130 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