【发布时间】:2010-11-04 06:25:46
【问题描述】:
我已经看到了在 PHP DOM 对象上使用 getNodePath() 方法的示例。
见:
http://www.php.net/manual/en/class.domdocument.php#91072
但是我找不到该方法的文档。
我一直在 DOM Docs 中兜圈子。
http://www.php.net/manual/en/book.dom.php
有什么想法吗?
【问题讨论】:
我已经看到了在 PHP DOM 对象上使用 getNodePath() 方法的示例。
见:
http://www.php.net/manual/en/class.domdocument.php#91072
但是我找不到该方法的文档。
我一直在 DOM Docs 中兜圈子。
http://www.php.net/manual/en/book.dom.php
有什么想法吗?
【问题讨论】:
并非所有方法和函数都记录在 PHP 手册中。如果你想找出一个类的方法,你可以使用Reflection。要么做
ReflectionClass::export('DOMNode');
或从命令行:
$ php --rc DOMNode
应该给出类似的东西:
Class [ <internal:dom> class DOMNode ] {
// ... lots of other stuff ...
Method [ <internal:dom> public method getNodePath ] {
- Parameters [0] {
}
}
// ... lots of other stuff ...
}
如果你为DOMDocument 这样做,它会告诉你它是从哪里继承的:
Method [ <internal:dom, inherits DOMNode> public method getNodePath ] {
- Parameters [0] {
}
}
顺便说一句,我不知道那个功能。便利!感谢您提出问题。
【讨论】:
您可以像这样创建自己的getNodeXPath():
<?php
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
$result='';
while ($parentNode = $node->parentNode) {
$nodeIndex=-1;
$nodeTagIndex=0;
do {
$nodeIndex++;
$testNode = $parentNode->childNodes->item( $nodeIndex );
if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
//echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
$nodeTagIndex++;
}
} while (!$node->isSameNode($testNode));
$result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
$node=$parentNode;
};
return $result;
}
?>
这是定义here。
【讨论】:
您链接到的示例表明哪些对象具有此方法:
case ($obj instanceof DOMDocument):
... $obj->getNodePath() ...
...
case ($obj instanceof DOMElement):
... $obj->getNodePath() ...
...
所以,DOMDocument 和 DOMElement 实例具有 getNodePath() 方法。但是,我无法在官方 PHP 文档中找到任何文档,但我发现了一篇显然由该方法的实现者撰写的博客文章:http://blog.liip.ch/archive/2006/07/16/added-domnode-getnodepath.html
【讨论】: