DOMNode クラス
(PHP 5, PHP 7, PHP 8)
クラス概要
bool
$exclusive
= false
,bool
$withComments
= false
,?array
$xpath
= null
,?array
$nsPrefixes
= null
): string|false
プロパティ
- nodeName
-
現在のノード型の正確な名前を返す
- nodeValue
-
その型に応じてノードの値を返す。 W3C の仕様とは異なり、 DOMElement ノードの値は
null
ではなく DOMNode::textContent と等しくなる。 - nodeType
-
ノードの型を、定義済みの定数 XML_xxx_NODE のいずれかで返す
- parentNode
-
このノードの親 (存在しない場合は
null
) を返す - parentElement
-
この要素の親要素。存在しない場合は
null
を返す - childNodes
-
このノードのすべての子を含む DOMNodeList。 子が存在しない場合は、空の DOMNodeList
- firstChild
-
このノードの最初の子。存在しない場合は
null
を返す - lastChild
-
このノードの最後の子。存在しない場合は
null
を返す - previousSibling
-
このノードの直前のノード。存在しない場合は
null
を返す - nextSibling
-
このノードの直後のノード。存在しない場合は
null
を返す - attributes
-
このノードが DOMElement の場合は ノードの属性を含む DOMNamedNodeMap、 それ以外の場合は
null
- isConnected
-
ノードが Document に接続されているかどうか
- ownerDocument
-
このノードに関連付けられている DOMDocument オブジェクト このノードが DOMDocument だった場合は、
null
- namespaceURI
-
このノードの名前空間 URI。指定されていない場合は
null
- prefix
-
このノードの名前空間プレフィックス
- localName
-
このノードの名前のローカル部分を返す
- baseURI
-
このノードの完全なベース URI。もし実装が完全な URL を できなかった場合は
null
- textContent
-
このノードとその子孫ノードのテキスト
変更履歴
バージョン | 説明 |
---|---|
8.3.0 | プロパティ DOMNode::$parentElement と DOMNode::$isConnected が追加されました。 |
8.0.0 | 実装されていなかったメソッド DOMNode::compareDocumentPosition(), DOMNode::isEqualNode(), DOMNode::getFeature(), DOMNode::setUserData(), DOMNode::getUserData() が削除されました。 |
注意
注意:
DOM拡張モジュール は UTF-8 エンコーディングを使います。他のエンコーディングを扱う場合は、mb_convert_encoding(), UConverter::transcode(), iconv() を使ってください。
目次
- DOMNode::appendChild — 子要素群の最後に新しい子要素を追加する
- DOMNode::C14N — ノードを文字列に正規化する
- DOMNode::C14NFile — ノードをファイルに正規化する
- DOMNode::cloneNode — ノードを複製する
- DOMNode::contains — ノードが別のノードを含んでいるかを調べる
- DOMNode::getLineNo — ノードが存在する行の番号を取得します。
- DOMNode::getNodePath — ノードの XPath を取得する
- DOMNode::getRootNode — ルート(根)ノードを取得する
- DOMNode::hasAttributes — ノードが属性を保持しているかどうかを調べる
- DOMNode::hasChildNodes — ノードが子を保持しているかどうかを調べる
- DOMNode::insertBefore — 参照しているノードの前に新しい子を追加する
- DOMNode::isDefaultNamespace — 指定した namespaceURI がデフォルトの名前空間かどうかを調べる
- DOMNode::isEqualNode — ノードが等しいかを調べる
- DOMNode::isSameNode — 2 つのノードが等しいかどうかを調べる
- DOMNode::isSupported — 指定したバージョンで機能がサポートされているかどうかを調べる
- DOMNode::lookupNamespaceURI — プレフィックスに基づいて、ノードの名前空間 URI を取得する
- DOMNode::lookupPrefix — 名前空間 URI に基づいて、ノードの名前空間プレフィックスを取得する
- DOMNode::normalize — ノードを正規化する
- DOMNode::removeChild — 子要素群から子要素を削除する
- DOMNode::replaceChild — 子を置き換える
User Contributed Notes 13 notes
It took me forever to find a mapping for the XML_*_NODE constants. So I thought, it'd be handy to paste it here:
1 XML_ELEMENT_NODE
2 XML_ATTRIBUTE_NODE
3 XML_TEXT_NODE
4 XML_CDATA_SECTION_NODE
5 XML_ENTITY_REFERENCE_NODE
6 XML_ENTITY_NODE
7 XML_PROCESSING_INSTRUCTION_NODE
8 XML_COMMENT_NODE
9 XML_DOCUMENT_NODE
10 XML_DOCUMENT_TYPE_NODE
11 XML_DOCUMENT_FRAGMENT_NODE
12 XML_NOTATION_NODE
You cannot simply overwrite $textContent, to replace the text content of a DOMNode, as the missing readonly flag suggests. Instead you have to do something like this:
<?php
$node->removeChild($node->firstChild);
$node->appendChild(new DOMText('new text content'));
?>
This example shows what happens:
<?php
$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
echo "Content 1: ".$node->textContent."\n";
$node->textContent = 'new content';
echo "Content 2: ".$node->textContent."\n";
$newText = new DOMText('new content');
$node->appendChild($newText);
echo "Content 3: ".$node->textContent."\n";
$node->removeChild($node->firstChild);
$node->appendChild($newText);
echo "Content 4: ".$node->textContent."\n";
?>
The output is:
Content 1: old content // starting content
Content 2: old content // trying to replace overwriting $node->textContent
Content 3: old contentnew content // simply appending the new text node
Content 4: new content // removing firstchild before appending the new text node
If you want to have a CDATA section, use this:
<?php
$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
$node->removeChild($node->firstChild);
$newText = $doc->createCDATASection('new cdata content');
$node->appendChild($newText);
echo "Content withCDATA: ".$doc->saveXML($node)."\n";
?>
For clarification:
The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.
See: http://www.php.net/manual/en/class.domelement.php
This class apparently also has a getElementsByTagName method.
I was able to confirm this by evaluating the output from DOMNodeList->item() against various tests with the is_a() function.
This class has a getAttribute method.
Assume that a DOMNode object $ref contained an anchor taken out of a DOMNode List. Then
$url = $ref->getAttribute('href');
would isolate the url associated with the href part of the anchor.
The issues around mixed content took me some experimentation to remember, so I thought I'd add this note to save others time.
When your markup is something like: <div><p>First text.</p><ul><li><p>First bullet</p></li></ul></div>, you'll get XML_ELEMENT_NODEs that are quite regular. The <div> has children <p> and <ul> and the nodeValue for both <p>s yields the text you expect.
But when your markup is more like <p>This is <b>bold</b> and this is <i>italic</i>.</p>, you realize that the nodeValue for XML_ELEMENT_NODEs is not reliable. In this case, you need to look at the <p>'s child nodes. For this example, the <p> has children: #text, <b>, #text, <i>, #text.
In this example, the nodeValue of <b> and <i> is the same as their #text children. But you could have markup like: <p>This <b>is bold and <i>bold italic</i></b>, you see?</p>. In this case, you need to look at the children of <b>, which will be #text, <i>, because the nodeValue of <b> will not be sufficient.
XML_TEXT_NODEs have no children and are always named '#text'. Depending on how whitespace is handled, your tree may have "empty" #text nodes as children of <body> and elsewhere.
Attributes are nodes, but I had forgotten that they are not in the tree expressed by childNodes. Walking the full tree using childNodes will not visit any attribute nodes.
Just discovered that node->nodeValue strips out all the tags
Yet another DOMNode to php array conversion function.
Other ones on this page are generating too "complex" arrays; this one should keep the array as tidy as possible.
Note: make sure to set LIBXML_NOBLANKS when calling DOMDocument::load, loadXML or loadHTML
See: http://be2.php.net/manual/en/libxml.constants.php
See: http://be2.php.net/manual/en/domdocument.loadxml.php
<?php
/**
* Returns an array representation of a DOMNode
* Note, make sure to use the LIBXML_NOBLANKS flag when loading XML into the DOMDocument
* @param DOMDocument $dom
* @param DOMNode $node
* @return array
*/
function nodeToArray( $dom, $node) {
if(!is_a( $dom, 'DOMDocument' ) || !is_a( $node, 'DOMNode' )) {
return false;
}
$array = false;
if( empty( trim( $node->localName ))) {// Discard empty nodes
return false;
}
if( XML_TEXT_NODE == $node->nodeType ) {
return $node->nodeValue;
}
foreach ($node->attributes as $attr) {
$array['@'.$attr->localName] = $attr->nodeValue;
}
foreach ($node->childNodes as $childNode) {
if ( 1 == $childNode->childNodes->length && XML_TEXT_NODE == $childNode->firstChild->nodeType ) {
$array[$childNode->localName] = $childNode->nodeValue;
} else {
if( false !== ($a = self::nodeToArray( $dom, $childNode))) {
$array[$childNode->localName] = $a;
}
}
}
return $array;
}
?>
In response to: alastair dot dallas at gmail dot com about "#text" nodes.
"#text" nodes appear when there are spaces or new lines between end tag and next initial tag.
Eg "<data><age>10</age>[SPACES]<other>20</other>[SPACES]</data>"
"data" childNodes has 4 childs:
- age = 10
- #text = spaces
- other = 20
- #text = spaces