CakeFest 2024: The Official CakePHP Conference

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DOMNode::getLineNoノードが存在する行の番号を取得します。

説明

public DOMNode::getLineNo(): int

パース時にノードが定義された行の番号を取得します。

パラメータ

この関数にはパラメータはありません。

戻り値

パース時にノードが定義された行の番号を返します。 ノードが手動で作成された場合、戻り値は 0 になります。

例1 DOMNode::getLineNo() メソッドの例

<?php
// 以下の例で使うXMLのダンプ
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<node />
</root>
XML;

// DOMDocumentクラスのインスタンスを生成する
$dom = new DOMDocument;

// XMLをロードする
$dom->loadXML($xml);

// <node> 要素が定義された行がどこにあるかを表示する
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

上の例の出力は以下となります。

The <node> tag is defined in line 3

add a note

User Contributed Notes 3 notes

up
4
ruud at vanmelick dot com
10 years ago
The 65535 line number limit is no longer a problem when you use libxml 2.9 or higher, but you have to explicitly enable support for big line numbers:

<?php
define
('XML_PARSE_BIG_LINES', 4194304);
$dom = new DOMDocument;
$dom->loadXML($xml, XML_PARSE_BIG_LINES);
?>
up
1
luke dot NOREPLY at webconnex dot com
13 years ago
This function is buggy. It doesn't always return the correct line number, especially for text elements. As an alternative you can do something like this:

<?php
$text
= $node->ownerDocument->saveXML($node);
$line += substr_count($text, "\n");
?>

You'll want to keep a reference to $line (starting at 0) and add to it as you parse over the document recursively.

In order for this to work you have to tell DOMDocument to preserve white space before loading the document.
up
0
Anonymous
11 years ago
The DOMNode::getLineNo() method doesn't work properly due to a libxml2 bug.

https://bugzilla.gnome.org/show_bug.cgi?id=676026
To Top