【问题标题】:PHP DOMDocument - trouble accessing list indexPHP DOMDocument - 访问列表索引时遇到问题
【发布时间】:2013-06-03 11:58:23
【问题描述】:

我正在为一个用 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; 访问 title 属性。它说它是未定义的,只有当我使用 foreach $title 作为 $theTitle 时,我才能访问这些值。我试过 $title[0]->nodeValue 和 $title->nodeValue(0) 从列表中检索第一个标题,但不幸的是无济于事。有点难过,快速的 google 并没有出现很多。

任何帮助将不胜感激!干杯,我也会继续寻找。

【问题讨论】:

  • 谢谢大家,我一发布就偶然发现了我需要的答案:D 感谢回复

标签: php domdocument


【解决方案1】:

您可以使用 XPath 解决这个问题:

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

$xpath = new DOMXPath($dom);

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

【讨论】:

  • XPath 被低估了。如果您打算使用 XML,那么您绝对必须了解 XPath。
  • 这就是我喜欢 XPath 的原因!这是解析网站的绝妙设备。
  • 谢谢大家,我一发布就偶然发现了我需要的答案:D 感谢回复
  • 答案是什么?接受你认为最有用的那个。
  • 虽然 XPath 是一个有趣的启示,并且两个答案都提供了我需要的语法,但我不得不勾选另一个。无论如何,为你的帮助干杯!
【解决方案2】:

试试这样的:

$title->item(0)->nodeValue;

http://www.php.net/manual/en/class.domnodelist.php

【讨论】:

  • 谢谢!这正是我所需要的。我是新用户,无法投票
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多