PHP DOMDocument -访问列表索引时遇到麻烦


PHP DOMDocument - trouble accessing list index

我正在为用php编写并在linux cli上运行的IRC bot编写一些代码。我有一个小麻烦与我的代码检索网站的标题标签,并使用DOMDocument NodeList显示它。基本上,在有两个或更多标签的网站上(你会惊讶于实际上有多少……)我只想处理第一个标题标签。从下面的代码中可以看到(它可以很好地处理一个或多个标记),有一个foreach块,它遍历每个标题标记。

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;它说它是未定义的,只有当我使用foreach $title作为$theTitle时,我才能访问值。我已经尝试了$title[0]->nodeValue和$title->nodeValue(0)从列表中检索第一个标题,但不幸的是无济于事。我有点难住了,谷歌一下也没有什么结果。

任何帮助都将非常感激!谢谢,我也会继续找的。

您可以使用XPath:

来解决这个问题
$dom = new DOMDocument();
@$dom->loadHTML($file);
$xpath = new DOMXPath($dom);
$title = $xpath->query('//title')->item(0)->nodeValue;

试试这样:

$title->item(0)->nodeValue;
http://www.php.net/manual/en/class.domnodelist.php