我正在为使用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)从列表中检索第一个标题,但不幸的是无济于事。有点难倒了,一个快速的谷歌并没有很多。
任何帮助将不胜感激!干杯,我会继续看。
谢谢你们我只要在我需要的答案迷迷糊糊的我贴:D欣赏回复 – Bryce