2011-01-06 75 views
2

我試圖解析美國大學和學院的數據庫的html頁面。我寫的代碼會取得大學的名字,但我無法取得他們各自的網址。如何在PHP中解析<a>標記的屬性值

public function fetch_universities() 
{ 
    $url = "http://www.utexas.edu/world/univ/alpha/"; 
    $dom = new DOMDocument(); 
    $html = $dom->loadHTMLFile($url); 
    $dom->preserveWhiteSpace = false; 
    $tables = $dom->getElementsByTagName('table'); 
    $tr = $tables->item(1)->getElementsByTagName('tr'); 
    $td = $tr->item(7)->getElementsByTagName('td'); 
    $rows = $td->item(0)->getElementsByTagName('li'); 

    $count = 0; 
    foreach ($rows as $row) 
    { 
     $count++; 
     $cols = $row->getElementsByTagName('a'); 
     echo "$count:".$cols->item(0)->nodeValue. "\n"; 
    } 
} 

這是我目前的代碼。

請告訴我如何獲取屬性值。

謝謝

回答

5

如果你有一個元素的引用,你只需要使用getAttribute(),所以大概:

echo "$count:".$cols->item(0)->getAttribute('href') . "\n";