2013-06-03 41 views
0

我正在爲使用php編寫的IRC bot編寫一些代碼,並在linux cli上運行。我在使用DOMDocument NodeList檢索網站標題標籤並顯示它時遇到了一些問題。基本上,在具有兩個或更多標籤的網站上(您會驚訝實際上有多少...)我只想處理第一個標題標籤。正如你可以從下面的代碼中看到的(這對於處理一個或多個標籤來說工作正常)有一個foreach塊,它遍歷每個標題標籤。PHP DOMDocument - 訪問列表索引時遇到的問題

public function onReceivedData($data) { 

    // loop through each message token 
    foreach ($data["message"] as $token) { 


    // if the token starts with www, add http file handle 
    if (strcmp(substr($token, 0, 4), "www.") == 0) { 

     $token = "http://" . $token; 

    } 

    // validate token as a URL 
    if (filter_var($token, FILTER_VALIDATE_URL)) { 

    // create timeout stream context 
    $theContext['http']['timeout'] = 3; 
    $context = stream_context_create($theContext); 
    // get contents of url 
    if ($file = file_get_contents($token, false, $context)) { 

     // instantiate a new DOMDocument object 
     $dom = new DOMDocument; 
     // load the html into the DOMDocument obj 
     @$dom->loadHTML($file); 
     // retrieve the title from the DOM node 
     // if assignment is valid then... 
     if ($title = $dom->getElementsByTagName("title")) { 
      // send a message to the channel 

      foreach ($title as $theTitle) { 

       $this->privmsg($data["target"], $theTitle->nodeValue); 

      } 

     } 

} else { 

     // notify of failure 
     $this->privmsg($data["target"], "Site could not be reached"); 

} 

} 

} 

} 

我更喜歡的是以某種方式限制它只處理第一個標題標記。我知道我可以用變量包圍一個if語句,以便它只響應一次,但我更注重使用「for」語句來處理單個迭代。但是,當我這樣做時,我無法使用$ title-> nodeValue訪問title屬性;它說它是未定義的,並且只有當我使用foreach $ title作爲$ theTitle時纔可以訪問這些值。我試過$ title [0] - > nodeValue和$ title-> nodeValue(0)從列表中檢索第一個標題,但不幸的是無濟於事。有點難倒了,一個快速的谷歌並沒有很多。

任何幫助將不勝感激!乾杯,我會繼續看。

+0

謝謝你們我只要在我需要的答案迷迷糊糊的我貼:D欣賞回覆 – Bryce

回答

2

您可以的XPath解決這個問題:

$dom = new DOMDocument(); 
@$dom->loadHTML($file); 

$xpath = new DOMXPath($dom); 

$title = $xpath->query('//title')->item(0)->nodeValue; 
+2

XPath被低估了。如果您打算使用XML,那麼您絕對有機會了解XPath。 – crush

+0

這就是爲什麼我喜歡XPath!這是一個很好的解析網站的工具。 – silkfire

+0

謝謝大家我一發現就偶然發現了我需要的答案:D欣賞回覆 – Bryce