2012-11-22 24 views
2

我想弄清楚如何解析一個網站,以獲得表中的鏈接。在我的特殊情況下有兩個表,但我只想要第二個表的鏈接(Link5 & Link6)。這是我想解析的HTML。我該如何解析一個網站以獲取表格中的鏈接?

<html> 
<head> 
</head> 
<body> 
<a href="http://www.example.com/link1.html">Link1</a><br> 
<br> 
<table> 
    <tbody> 
    <tr> 
     <td><a href="http://www.example.com/link2.html">Link2</a></td> 
     <td>dog</td> 
     <td>fish</td> 
    </tr> 
    <tr> 
     <td><a href="http://www.example.com/link3.html">Link3</a></td> 
     <td>cat</td> 
     <td>bird</td> 
    </tr> 
    </tbody> 
</table> 
<br> 
<a href="http://www.example.com/link4.html">Link4</a><br> 
<br> 
<table> 
    <tbody> 
    <tr> 
     <td><a href="http://www.example.com/link5.html">Link5</a></td> 
     <td>cow</td> 
    </tr> 
    <tr> 
     <td><a href="http://www.example.com/link6.html">Link6</a></td> 
     <td>horse</td> 
    </tr> 
    </tbody> 
</table> 
<br> 
<a href="http://www.example.com/link7.html">Link7</a><br> 
</body> 
</html> 

我讀過DOM是解析網絡數據的好方法,所以這裏是我一直在研究的代碼。

<?php 
$link = array(); 

//new dom object 
$dom = new DOMDocument(); 

//load the html 
$html = $dom->loadHTMLFile('http://www.example.com'); 

//discard white space 
$dom->preserveWhiteSpace = false; 

//get the table by its tag name 
$tables = $dom->getElementsByTagName('table'); 

$rows = $tables->item(1)->getElementsByTagName('tr'); 

$i = 0; 

//loop over the table rows 
foreach ($rows as $row) 
{ 
    $links = $row->getElementsByTagName('a'); 


    //put node value into an array 
    $link[] = $links->item(0)->nodeValue; 

    // echo the values 
    echo $link[$i] . '<br />'; 

    $i++; 
} 

?> 

該代碼給出了以下的輸出: Link5 Link6

但我想實現的是: http://www.example.com/link5.html http://www.example.com/link6.html

任何幫助將不勝感激。

回答

0

我想問題是你想得到的href不是節點的值。所以你應該使用getAttribute

+0

嗨Naryl。感謝您的信息,我終於得到了我的代碼工作感謝你和looper。 –

+0

酷,很高興它幫助! – Naryl

0
$link[] = $links->item(0)->getAttribute("href"); 
+0

嗨looper。感謝您的快速回復。這段代碼完美無缺。非常感謝!! –

相關問題