如何在PHP中解析标记的属性值

问题描述:

我试图解析美国大学和学院的数据库的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"; 
    } 
} 

这是我目前的代码。

请告诉我如何获取属性值。

谢谢

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

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