0

PHP で記述され、Linux CLI で実行される IRC ボットのコードを書いています。Web サイトのタイトル タグを取得し、DOMDocument NodeList を使用して表示するコードに少し問題があります。基本的に、2 つ以上のタグを持つ Web サイト (そして、実際にどれだけ多くのタグが存在するかに驚かれることでしょう...) では、最初のタイトル タグのみを処理したいと考えています。以下のコード (1 つまたは複数のタグを処理するために正常に動作しています) からわかるように、各タイトル タグを反復処理する 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) を試しましたが、残念ながら役に立ちませんでした。少し困惑し、簡単なグーグルはあまり現れませんでした。

どんな助けでも大歓迎です!乾杯、私も探し続けます。

4

2 に答える 2

2

これはXPathで解決できます:

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

$xpath = new DOMXPath($dom);

$title = $xpath->query('//title')->item(0)->nodeValue;
于 2013-06-03T12:02:19.340 に答える
0

次のようなことを試してください:

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

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

于 2013-06-03T12:02:09.747 に答える