Webエンジニア向けプログラミング解説動画をYouTubeで配信中!
▶ チャンネル登録はこちら

【PHP8.x】Dom\Text::compareDocumentPosition()メソッドの使い方

compareDocumentPositionメソッドの使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

compareDocumentPositionメソッドは、現在のDOMノードと、引数として指定された別のDOMノードとの相対的な位置関係を比較するメソッドです。このメソッドはDom\Textクラスに属しており、XMLやHTMLドキュメントの構造内でノードがどのように配置されているかを知るために使用されます。

このメソッドは、比較したい別のDom\Nodeオブジェクトを引数として受け取ります。戻り値は、2つのノード間の関係を示すビットマスクとしてエンコードされた整数値です。具体的には、以下のいずれか、またはそれらの組み合わせを示す定数値が返されます。DOM_DOCUMENT_POSITION_DISCONNECTEDは、ノードが異なるツリーに存在するか、あるいは比較できない状態であることを示します。DOM_DOCUMENT_POSITION_PRECEDINGは、比較対象ノードの前に現在のノードが位置していることを示し、DOM_DOCUMENT_POSITION_FOLLOWINGはその後に位置していることを示します。DOM_DOCUMENT_POSITION_CONTAINSは、現在のノードが比較対象ノードを含んでいることを意味し、DOM_DOCUMENT_POSITION_CONTAINED_BYは、その逆で現在のノードが比較対象ノードに含まれていることを示します。また、DOM_DOCUMENT_POSITION_SAME_NODEは、2つのノードが全く同じノードであることを表します。

システムエンジニアがDOM操作を行う際、特定のノードが別のノードに対して親子関係にあるのか、兄弟関係にあるのか、あるいは全く関係がないのかをプログラム的に判断する必要がある場合に、このメソッドは非常に有用です。PHP 8以降でDOM拡張機能が有効な環境で利用可能です。

構文(syntax)

1<?php
2
3$dom = new DOMDocument();
4$dom->loadXML('<root><element>Text Content</element><other>Another Text</other></root>');
5
6// Dom\Text インスタンスを取得
7$textNode = $dom->getElementsByTagName('element')->item(0)->firstChild;
8
9// 比較対象の Dom\Node インスタンスを取得 (Dom\Element は Dom\Node を継承)
10$otherNode = $dom->getElementsByTagName('other')->item(0);
11
12// Dom\Text::compareDocumentPosition メソッドの呼び出し
13$positionResult = $textNode->compareDocumentPosition($otherNode);

引数(parameters)

Dom\Node $other

  • Dom\Node $other: 比較対象となる別のDOMノード

戻り値(return)

int

このメソッドは、現在のノードと指定されたノードの位置関係を示す整数値を返します。返される値は、ビットフラグとして解釈され、ノード間の比較結果を示します。

サンプルコード

PHP DOMテキストノード位置比較

1<?php
2
3namespace App\DomExamples;
4
5use DOMDocument;
6use DOMElement;
7use DOMXPath;
8use DOMText;
9use Dom\Node; // Using the Dom\Node interface for type hints and constants as per reference (PHP 8.1+)
10
11/**
12 * Provides utility methods for comparing DOM node positions.
13 *
14 * This class demonstrates the usage of `Dom\Text::compareDocumentPosition`.
15 * It is structured with docblocks suitable for phpDocumentor, and
16 * uses a namespace, implying a project setup managed by Composer for autoloading.
17 */
18class DomPositionComparer
19{
20    /**
21     * Compares the position of a `Dom\Text` node with another `Dom\Node` within a document.
22     *
23     * This method showcases how to use `Dom\Text::compareDocumentPosition`
24     * to determine the relative position of two nodes. The return value is a bitmask
25     * indicating various relationships (disconnected, preceding, following, contains, etc.).
26     *
27     * @param string $htmlString     The HTML string to parse into a DOM document.
28     * @param string $textNodeXPath  The XPath to locate the primary `Dom\Text` node.
29     * @param string $otherNodeXPath The XPath to locate the secondary `Dom\Node` for comparison.
30     * @return array<string, mixed>  Returns an associative array with the comparison result (bitmask)
31     *                               and a human-readable interpretation of the flags, along with node details.
32     * @throws \Exception If nodes cannot be found or the located primary node is not a `Dom\Text` instance.
33     *
34     * @phpdocumentor This method includes docblocks that can be processed by phpDocumentor
35     *                to generate API documentation for your project.
36     * @composer The namespace structure and class definition are typical for projects
37     *           using Composer for dependency management and autoloading.
38     */
39    public function compareTextNodePositions(
40        string $htmlString,
41        string $textNodeXPath,
42        string $otherNodeXPath
43    ): array {
44        $dom = new DOMDocument('1.0', 'UTF-8');
45        // Suppress errors for potentially malformed HTML to simplify the example.
46        // In a production environment, robust error handling for loadHTML is crucial.
47        @$dom->loadHTML($htmlString);
48
49        $xpath = new DOMXPath($dom);
50
51        // Find the primary text node (the one calling compareDocumentPosition)
52        $textNodeList = $xpath->query($textNodeXPath);
53        if ($textNodeList->length === 0) {
54            throw new \Exception("Primary Dom\Text node not found for XPath: {$textNodeXPath}");
55        }
56        // DOMText is the concrete class implementing Dom\Text in PHP 8.1+
57        $textNode = $textNodeList->item(0);
58        if (!$textNode instanceof DOMText) {
59            throw new \Exception("Node found for XPath '{$textNodeXPath}' is not a Dom\Text node (got " . get_class($textNode) . ").");
60        }
61
62        // Find the other node for comparison (the argument to compareDocumentPosition)
63        $otherNodeList = $xpath->query($otherNodeXPath);
64        if ($otherNodeList->length === 0) {
65            throw new \Exception("Other Dom\Node not found for XPath: {$otherNodeXPath}");
66        }
67        $otherNode = $otherNodeList->item(0);
68        // $otherNode can be any type of Dom\Node (e.g., DOMElement, DOMText, etc.).
69
70        // Perform the comparison using Dom\Text::compareDocumentPosition
71        // The $textNode object compares its position relative to $otherNode.
72        $comparisonResult = $textNode->compareDocumentPosition($otherNode);
73
74        $interpretation = [];
75        // Interpret the bitmask result using constants from Dom\Node
76        if ($comparisonResult & Node::DOCUMENT_POSITION_DISCONNECTED) {
77            $interpretation[] = 'Disconnected: The nodes are in different documents or subtrees and cannot be compared directly.';
78        }
79        if ($comparisonResult & Node::DOCUMENT_POSITION_PRECEDING) {
80            $interpretation[] = 'Preceding: The other node comes before the reference text node in document order.';
81        }
82        if ($comparisonResult & Node::DOCUMENT_POSITION_FOLLOWING) {
83            $interpretation[] = 'Following: The other node comes after the reference text node in document order.';
84        }
85        if ($comparisonResult & Node::DOCUMENT_POSITION_CONTAINS) {
86            // This flag means the reference node ($textNode) contains the other node.
87            // A text node cannot contain other nodes, so this flag is typically not set here.
88            $interpretation[] = 'Contains: The reference text node contains the other node (unlikely for text nodes).';
89        }
90        if ($comparisonResult & Node::DOCUMENT_POSITION_CONTAINED_BY) {
91            // This flag means the other node contains the reference node ($textNode).
92            $interpretation[] = 'Contained By: The other node contains the reference text node.';
93        }
94        if ($comparisonResult & Node::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC) {
95            $interpretation[] = 'Implementation Specific: The comparison involves platform- or implementation-specific behavior.';
96        }
97
98        // Prepare a user-friendly display string for the other node for better output clarity
99        $otherNodeDisplay = '';
100        if ($otherNode instanceof DOMText) {
101            $value = $otherNode->nodeValue;
102            $otherNodeDisplay = "'" . substr($value, 0, 30) . (strlen($value) > 30 ? '...' : '') . "' (text node)";
103        } elseif ($otherNode instanceof DOMElement) {
104            $otherNodeDisplay = "<" . $otherNode->nodeName . "> (element)";
105        } else {
106            $otherNodeDisplay = "'" . $otherNode->nodeName . "' (node type: " . $otherNode->nodeType . ")";
107        }
108
109        return [
110            'result'             => $comparisonResult,
111            'interpretation'     => $interpretation,
112            'text_node_value'    => $textNode->nodeValue,
113            'other_node_display' => $otherNodeDisplay,
114        ];
115    }
116}
117
118// --- Example Usage for System Engineers ---
119// This part demonstrates how you might use the class in a script.
120// In a Composer-managed project, this class would typically be autoloaded automatically
121// when you include Composer's autoloader (`require __DIR__ . '/vendor/autoload.php';`).
122
123$html = <<<HTML
124<html>
125<head><title>Document Position Test</title></head>
126<body>
127    <div id="wrapper">
128        <p>This is some <span>important</span> text.</p>
129        <div>
130            Another block of content.
131            <span>More text</span> here.
132        </div>
133    </div>
134</body>
135</html>
136HTML;
137
138// Instantiate the comparer class
139$comparer = new App\DomExamples\DomPositionComparer();
140
141echo "--- Demonstrating Dom\\Text::compareDocumentPosition ---\n\n";
142
143// Example 1: Comparing a text node with its containing paragraph element
144try {
145    // Reference text node: "important" (inside a <span> within a <p>)
146    $textNodeXPath1 = "//p/span/text()";
147    // Node to compare against: The <p> element that contains the text node
148    $otherNodeXPath1 = "//div[@id='wrapper']/p";
149
150    $result1 = $comparer->compareTextNodePositions($html, $textNodeXPath1, $otherNodeXPath1);
151    echo "Comparison 1: Reference Text Node ('" . $result1['text_node_value'] . "') vs. " . $result1['other_node_display'] . "\n";
152    echo "Raw Result (Bitmask): " . $result1['result'] . " (Decimal)\n";
153    echo "Interpretation:\n";
154    foreach ($result1['interpretation'] as $line) {
155        echo "  - " . $line . "\n";
156    }
157    echo "\n";
158    // Expected: DOM_DOCUMENT_POSITION_PRECEDING (0x02) | DOM_DOCUMENT_POSITION_CONTAINED_BY (0x10) = 18.
159    // Explanation: The <p> element (other node) precedes the "important" text node (reference node) in document order,
160    // and the <p> element also contains the "important" text node.
161
162} catch (\Exception $e) {
163    echo "Error in Comparison 1: " . $e->getMessage() . "\n\n";
164}
165
166// Example 2: Comparing a text node with an element that follows it
167try {
168    // Reference text node: "important"
169    $textNodeXPath2 = "//p/span/text()";
170    // Node to compare against: The <div> element that appears after the <p>
171    $otherNodeXPath2 = "//div[@id='wrapper']/div[1]";
172
173    $result2 = $comparer->compareTextNodePositions($html, $textNodeXPath2, $otherNodeXPath2);
174    echo "Comparison 2: Reference Text Node ('" . $result2['text_node_value'] . "') vs. " . $result2['other_node_display'] . "\n";
175    echo "Raw Result (Bitmask): " . $result2['result'] . " (Decimal)\n";
176    echo "Interpretation:\n";
177    foreach ($result2['interpretation'] as $line) {
178        echo "  - " . $line . "\n";
179    }
180    echo "\n";
181    // Expected: DOM_DOCUMENT_POSITION_FOLLOWING (0x04) = 4.
182    // Explanation: The <div> element (other node) follows the "important" text node (reference node) in document order.
183
184} catch (\Exception $e) {
185    echo "Error in Comparison 2: " . $e->getMessage() . "\n\n";
186}
187
188// Example 3: Comparing two different text nodes in sequence within the same paragraph
189try {
190    // Reference text node: "This is some " (the first text node inside the <p>)
191    $textNodeXPath3 = "//p/text()[1]";
192    // Node to compare against: "important" (the text node inside <span> within <p>)
193    $otherNodeXPath3 = "//p/span/text()";
194
195    $result3 = $comparer->compareTextNodePositions($html, $textNodeXPath3, $otherNodeXPath3);
196    echo "Comparison 3: Reference Text Node ('" . $result3['text_node_value'] . "') vs. " . $result3['other_node_display'] . "\n";
197    echo "Raw Result (Bitmask): " . $result3['result'] . " (Decimal)\n";
198    echo "Interpretation:\n";
199    foreach ($result3['interpretation'] as $line) {
200        echo "  - " . $line . "\n";
201    }
202    echo "\n";
203    // Expected: DOM_DOCUMENT_POSITION_FOLLOWING (0x04) = 4.
204    // Explanation: The "important" text node (other node) follows "This is some " (reference node) in document order.
205
206} catch (\Exception $e) {
207    echo "Error in Comparison 3: " . $e->getMessage() . "\n\n";
208}

PHP 8以降で利用可能なDom\TextクラスのcompareDocumentPositionメソッドは、HTMLやXML文書内のテキストノードと、他の任意のDOMノード(要素、別のテキストノードなど)との相対的な位置関係を判別するための機能です。

このメソッドはDom\Node型の引数$otherとして比較対象のノードを受け取ります。そして、呼び出し元のテキストノードが引数のノードに対して、文書内でどのような位置にあるかを示す整数値(ビットマスク)を戻り値として返します。この整数値は、Dom\Nodeクラスの定数(例:Node::DOCUMENT_POSITION_PRECEDING、Node::DOCUMENT_POSITION_FOLLOWING、Node::DOCUMENT_POSITION_CONTAINS、Node::DOCUMENT_POSITION_CONTAINED_BYなど)をビット論理演算で組み合わせることで、ノード間の詳細な関係を特定できます。

例えば、サンプルコードの例では、テキストノードがその親要素に対して「含まれている」(CONTAINED_BY)関係にあることや、文書内の別の要素に「後続している」(FOLLOWING)関係にあることなどを検出しています。この機能は、動的なウェブコンテンツの解析や、文書構造に基づいた複雑なデータ抽出ロジックを実装する際に、ノード間の正確な順序や包含関係をプログラム的に判断する上で非常に強力なツールとなります。文書構造を扱うシステム開発において、ノードの相対位置を厳密にチェックする必要がある場面で活用できます。

compareDocumentPositionメソッドは、二つのDOMノード間の相対的な位置関係を数値のビットマスクで返します。この戻り値はDom\Nodeインターフェースで定義されている定数(例: Node::DOCUMENT_POSITION_PRECEDING)を用いて解釈する必要があり、複数の状態が同時に示されることに注意が必要です。このメソッドを呼び出す側のノードはDOMTextクラスのインスタンスである必要がありますが、比較対象のノードはDOMElementを含む任意のDom\Nodeを実装したノードが指定可能です。サンプルコード中の@演算子によるDOMDocument::loadHTMLのエラー抑制は、本番環境では堅牢なエラーハンドリングに置き換えてください。また、XPathによるノード特定は、パスが不正確な場合にノードが見つからず例外が発生するため、正確な記述が重要です。

PHP DOM Textノードの位置比較

1<?php
2
3/**
4 * Dom\Text::compareDocumentPosition メソッドの使用例を示します。
5 *
6 * このファイルは、phpDocumentor がPHPDocコメントをどのように解析し、
7 * コードのドキュメントを生成するかを間接的に示しています。
8 * phpDocumentorは、このようなコメントからAPIドキュメントを生成するために
9 * さまざまなオプション(設定)を提供しています。
10 */
11
12/**
13 * 2つのDOMノードのドキュメント内での相対位置を比較し、その結果を出力します。
14 *
15 * `Dom\Text::compareDocumentPosition` メソッドは、呼び出し元のノードから見て
16 * 引数で指定されたノードがドキュメント内でどの位置にあるかを示すビットマスク(整数)を返します。
17 * このビットマスクは、`DOM_DOCUMENT_POSITION_*` 定数と論理AND演算を行うことで、
18 * 具体的な位置関係を特定できます。
19 *
20 * @param Dom\Node $node1 比較の基準となる最初のノード(このノードのメソッドを呼び出す)。
21 * @param Dom\Node $node2 比較対象となる2番目のノード。
22 * @return void 結果は標準出力に出力されます。
23 */
24function demonstrateCompareDocumentPosition(Dom\Node $node1, Dom\Node $node2): void
25{
26    echo "--- 比較対象 ---\n";
27    echo "ノード1 (呼び出し元): '{$node1->nodeValue}'\n";
28    echo "ノード2 (引数): '{$node2->nodeValue}'\n";
29
30    // Dom\Node クラスに定義されている compareDocumentPosition メソッドを呼び出す
31    // Dom\Text は Dom\Node を継承しているので、このメソッドを利用できます。
32    $position = $node1->compareDocumentPosition($node2);
33
34    echo "結果 (ビットマスク): " . sprintf("0x%02X", $position) . "\n";
35    echo "解釈:\n";
36
37    // 戻り値のビットマスクを解釈し、各位置関係を出力
38    if ($position === 0) {
39        echo " - ノードは同じです。\n";
40    }
41    if ($position & DOM_DOCUMENT_POSITION_DISCONNECTED) {
42        echo " - ノードは互いに接続されていません(異なるドキュメントツリーまたは未接続)。\n";
43    }
44    if ($position & DOM_DOCUMENT_POSITION_PRECEDING) {
45        echo " - ノード2はノード1より前にあります(ドキュメント順)。\n";
46    }
47    if ($position & DOM_DOCUMENT_POSITION_FOLLOWING) {
48        echo " - ノード2はノード1より後にあります(ドキュメント順)。\n";
49    }
50    if ($position & DOM_DOCUMENT_POSITION_CONTAINS) {
51        echo " - ノード1はノード2を含んでいます(ノード2はノード1の子孫)。\n";
52    }
53    if ($position & DOM_DOCUMENT_POSITION_CONTAINED_BY) {
54        echo " - ノード1はノード2に含まれています(ノード1はノード2の祖先)。\n";
55    }
56    if ($position & DOM_DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC) {
57        echo " - 実装固有の比較結果が含まれています。\n";
58    }
59    echo "\n";
60}
61
62// --- サンプルコード実行部分 ---
63
64// 1. Dom\Document インスタンスの作成
65$doc = new Dom\Document();
66$root = $doc->createElement('root');
67$doc->appendChild($root); // ルート要素をドキュメントに追加
68
69// 2. 複数の Dom\Text ノードを作成し、ドキュメントツリーに追加
70$textNode1 = $doc->createTextNode('Hello');
71$root->appendChild($textNode1); // root の子として textNode1 を追加
72
73$elementSpan = $doc->createElement('span');
74$root->appendChild($elementSpan); // root の子として span を追加
75
76$textNode2 = $doc->createTextNode('World');
77$elementSpan->appendChild($textNode2); // span の子として textNode2 を追加
78
79$textNode3 = $doc->createTextNode('PHP');
80$root->appendChild($textNode3); // root の子として textNode3 を追加 (textNode2の後に位置)
81
82// 3. ドキュメントツリーに接続されていない Dom\Text ノード
83$disconnectedTextNode = $doc->createTextNode('Disconnected');
84
85// さまざまな組み合わせで比較を実行し、結果を出力します。
86echo "## Dom\\Text::compareDocumentPosition の使用例 ##\n\n";
87
88// 例1: textNode1 (Hello) と textNode2 (World) の比較
89// textNode1 は textNode2 より前に位置します。
90demonstrateCompareDocumentPosition($textNode1, $textNode2);
91
92// 例2: textNode2 (World) と textNode1 (Hello) の比較
93// textNode2 は textNode1 より後に位置します。
94demonstrateCompareDocumentPosition($textNode2, $textNode1);
95
96// 例3: textNode1 (Hello) と textNode3 (PHP) の比較
97// textNode1 は textNode3 より前に位置します。
98demonstrateCompareDocumentPosition($textNode1, $textNode3);
99
100// 例4: textNode3 (PHP) と textNode1 (Hello) の比較
101// textNode3 は textNode1 より後に位置します。
102demonstrateCompareDocumentPosition($textNode3, $textNode1);
103
104// 例5: textNode1 (Hello) と自身 (textNode1) の比較
105// ノードは同じです。
106demonstrateCompareDocumentPosition($textNode1, $textNode1);
107
108// 例6: textNode1 (Hello) とドキュメントツリーに接続されていないノードの比較
109// ノードは互いに接続されていません。
110demonstrateCompareDocumentPosition($textNode1, $disconnectedTextNode);

PHP 8のDom\Text::compareDocumentPositionメソッドは、DOMドキュメントツリー内にある二つのノードの相対的な位置関係を比較するために使用されます。このメソッドは、呼び出し元のDom\Textノード(Dom\TextはDom\Nodeを継承しているため、実質的にすべてのDom\Node型で利用可能です)から見て、引数として指定されたDom\Node $otherがドキュメント内でどこに位置するかを判定します。

メソッドは整数値を返しますが、これは複数の位置関係を同時に示すビットマスクです。この戻り値は、PHPのDOM_DOCUMENT_POSITION_*という定数群と論理AND演算を行うことで、「ノードが同じである」「ノードが互いに接続されていない」「呼び出し元のノードより前に位置する」「呼び出し元のノードより後に位置する」「呼び出し元のノードが引数のノードを含んでいる(親である)」「呼び出し元のノードが引数のノードに含まれている(子孫である)」といった具体的な位置関係を特定できます。例えば、ドキュメント内のテキストノードが別のテキストノードに対して物理的にどの順序で出現するか、あるいは親子関係にあるかを調べたい場合に活用されます。

このメソッドは、2つのDOMノードのドキュメント内での相対位置を比較します。戻り値は単なる整数ではなく、DOM_DOCUMENT_POSITION_*定数と論理AND演算子&を使って個々の位置関係を解釈する必要がある点に注意してください。Dom\Textクラスのメソッドですが、Dom\Nodeを継承したあらゆるノード(例: Dom\Element)と比較可能です。比較対象のノードが同じドキュメントツリーに接続されているかどうかで結果が変わるため、特に未接続ノードとの比較ではDOM_DOCUMENT_POSITION_DISCONNECTEDが返されることを理解しておくことが重要です。

関連コンテンツ

関連IT用語

関連プログラミング言語